<template>
    <Card class="expense-overview">
        <div v-if="loading" class="loading-state">
            <div class="skeleton-header"></div>
            <div class="skeleton-balance"></div>
            <div class="skeleton-tabs"></div>
            <div class="skeleton-content"></div>
        </div>

        <div v-else-if="error" class="error-state">
            <Alert type="error" :message="error" />
            <Button @click="loadFinancials" class="mt-4">Retry</Button>
        </div>

        <div v-else class="content-loaded">
            <div class="overview-header">
                <div class="balance-section">
                    <span class="balance-label">Your Net Balance</span>
                    <h2 class="net-balance" :class="balanceColorClass">
                        {{ formatCurrency(netBalance, currency) }}
                    </h2>
                    <p class="balance-subtitle" :class="balanceColorClass">
                        {{ balanceStatusText }}
                    </p>
                </div>
                <div class="overall-spending">
                    <span class="spending-label">Total Group Spending</span>
                    <p class="spending-amount">
                        {{ formatCurrency(totalGroupSpending, currency) }}
                    </p>
                </div>
            </div>

            <Tabs v-model="selectedTab" class="mt-6">
                <div class="tab-list">
                    <button v-for="tab in tabs" :key="tab.id"
                        :class="['tab-item', { 'is-active': selectedTab === tab.id }]" @click="selectedTab = tab.id">
                        {{ tab.name }}
                    </button>
                </div>

                <div class="tab-panels">
                    <div v-if="selectedTab === 'summary'" class="tab-panel">
                        <ul v-if="debts.length > 0 || credits.length > 0" class="debt-credit-list">
                            <li v-for="credit in credits" :key="`credit-${credit.user.id}`"
                                class="list-item text-success">
                                <span>{{ credit.user.name }} owes you</span>
                                <span class="font-mono font-semibold">{{ formatCurrency(credit.amount, currency)
                                    }}</span>
                            </li>
                            <li v-for="debt in debts" :key="`debt-${debt.user.id}`" class="list-item text-danger">
                                <span>You owe {{ debt.user.name }}</span>
                                <span class="font-mono font-semibold">{{ formatCurrency(debt.amount, currency) }}</span>
                            </li>
                        </ul>
                        <div v-else class="empty-tab">
                            <p>You are all settled up. Good job!</p>
                        </div>
                    </div>

                    <div v-if="selectedTab === 'transactions'" class="tab-panel">
                        <!-- This would be a list of recent transactions -->
                        <div class="empty-tab">
                            <p>Transaction history coming soon.</p>
                        </div>
                    </div>

                    <div v-if="selectedTab === 'graph'" class="tab-panel">
                        <!-- Placeholder for debt graph -->
                        <div class="empty-tab">
                            <p>Debt graph visualization coming soon.</p>
                        </div>
                    </div>
                </div>
            </Tabs>
        </div>
    </Card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { apiClient } from '@/services/api'
import { Card, Button, Alert, Tabs } from '@/components/ui'
import { API_ENDPOINTS } from '@/config/api-config'

// Props
const props = defineProps<{
    groupId?: number | string
}>()

// State
const loading = ref(true)
const error = ref<string | null>(null)
const summary = ref<any>(null)

type Tab = 'summary' | 'transactions' | 'graph';
const selectedTab = ref<Tab>('summary')
const currency = ref('USD')

const tabs: { id: Tab; name: string }[] = [
    { id: 'summary', name: 'Summary' },
    { id: 'transactions', name: 'Transactions' },
    { id: 'graph', name: 'Graph' },
]

// API Call
const loadFinancials = async () => {
    loading.value = true
    error.value = null
    try {
        const endpoint = props.groupId
            ? API_ENDPOINTS.FINANCIALS.GROUP_SUMMARY(props.groupId.toString())
            : API_ENDPOINTS.FINANCIALS.USER_SUMMARY
        const { data } = await apiClient.get(endpoint)
        summary.value = data
        if (data.currency) {
            currency.value = data.currency
        }
    } catch (err: any) {
        error.value = err.response?.data?.detail || 'Failed to load financial summary.'
    } finally {
        loading.value = false
    }
}

// Computed Properties
const netBalance = computed(() => summary.value?.net_balance || 0)
const totalGroupSpending = computed(() => summary.value?.total_group_spending || 0)
const debts = computed(() => summary.value?.debts || [])
const credits = computed(() => summary.value?.credits || [])

const balanceColorClass = computed(() => {
    if (netBalance.value > 0) return 'text-success'
    if (netBalance.value < 0) return 'text-danger'
    return 'text-neutral-900'
})

const balanceStatusText = computed(() => {
    if (netBalance.value > 0) return "You are owed money"
    if (netBalance.value < 0) return "You owe money"
    return "You are all settled up"
})

// Formatters
const formatCurrency = (amount: number, currencyCode: string) => {
    try {
        return new Intl.NumberFormat(undefined, { style: 'currency', currency: currencyCode }).format(amount)
    } catch {
        return `${amount.toFixed(2)} ${currencyCode}`
    }
}

// Lifecycle
onMounted(() => {
    loadFinancials()
})
</script>

<style scoped>
.expense-overview {
    @apply p-6;
}

/* Loading Skeleton */
.loading-state {
    @apply animate-pulse space-y-6;
}

.skeleton-header {
    @apply h-16 bg-neutral-200 rounded-lg;
}

.skeleton-balance {
    @apply h-10 w-3/4 bg-neutral-200 rounded;
}

.skeleton-tabs {
    @apply h-8 w-1/2 bg-neutral-200 rounded;
}

.skeleton-content {
    @apply h-24 bg-neutral-200 rounded-lg;
}

/* Error State */
.error-state {
    @apply text-center;
}

/* Content */
.overview-header {
    @apply flex justify-between items-start pb-4 border-b border-neutral-200;
}

.balance-label,
.spending-label {
    @apply text-sm text-neutral-600 mb-1;
}

.net-balance {
    @apply text-3xl font-bold;
}

.balance-subtitle {
    @apply text-sm font-medium;
}

.overall-spending {
    @apply text-right;
}

.spending-amount {
    @apply text-xl font-semibold text-neutral-800;
}

/* Tabs */
.tab-list {
    @apply flex border-b border-neutral-200;
}

.tab-item {
    @apply px-4 py-2 text-sm font-medium text-neutral-600 border-b-2 border-transparent;
    @apply hover:bg-neutral-100 hover:text-neutral-800 transition-colors;
}

.tab-item.is-active {
    @apply text-primary border-primary;
}

.tab-panels {
    @apply pt-6;
}

/* Debt/Credit List */
.debt-credit-list {
    @apply space-y-3;
}

.list-item {
    @apply flex justify-between items-center p-3 bg-neutral-50 rounded-lg;
}

.text-success {
    @apply text-green-600;
}

.list-item.text-success {
    @apply bg-green-50;
}

.text-danger {
    @apply text-red-600;
}

.list-item.text-danger {
    @apply bg-red-50;
}

/* Empty State for Tabs */
.empty-tab {
    @apply text-center text-neutral-500 py-8;
}
</style>