<template>
    <Card class="financial-summary-card">
        <div class="summary-header">
            <h3 class="summary-title">Financial Summary</h3>
            <p class="summary-subtitle">Your financial position in this group</p>
        </div>

        <div v-if="loading" class="summary-loading">
            <Spinner label="Loading financial summary..." />
        </div>

        <Alert v-else-if="error" type="error" :message="error" />

        <div v-else-if="summary" class="summary-content">
            <!-- Net Balance -->
            <div class="net-balance-section">
                <div class="balance-amount" :class="balanceColorClass">
                    {{ formatCurrency(summary.net_balance, summary.currency) }}
                </div>
                <div class="balance-status">
                    {{ getBalanceStatusText(summary.net_balance) }}
                </div>
            </div>

            <!-- Overall Group Spending -->
            <div class="spending-section">
                <div class="spending-label">Total Group Spending</div>
                <div class="spending-amount">
                    {{ formatCurrency(summary.total_group_spending, summary.currency) }}
                </div>
            </div>

            <!-- Debts & Credits -->
            <div v-if="summary.debts.length > 0 || summary.credits.length > 0" class="debts-credits-section">
                <!-- You Owe -->
                <div v-if="summary.debts.length > 0" class="debts-section">
                    <h4 class="section-title">You Owe</h4>
                    <div class="debt-credit-list">
                        <div v-for="debt in summary.debts" :key="debt.user.id" class="debt-credit-item debt">
                            <div class="user-info">
                                <span class="user-name">{{ debt.user.name }}</span>
                            </div>
                            <div class="amount amount-debt">
                                {{ formatCurrency(debt.amount, summary.currency) }}
                            </div>
                        </div>
                    </div>
                </div>

                <!-- You Are Owed -->
                <div v-if="summary.credits.length > 0" class="credits-section">
                    <h4 class="section-title">You Are Owed</h4>
                    <div class="debt-credit-list">
                        <div v-for="credit in summary.credits" :key="credit.user.id" class="debt-credit-item credit">
                            <div class="user-info">
                                <span class="user-name">{{ credit.user.name }}</span>
                            </div>
                            <div class="amount amount-credit">
                                {{ formatCurrency(credit.amount, summary.currency) }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- All Settled -->
            <div v-else class="all-settled">
                <BaseIcon name="heroicons:check-circle-solid" class="w-8 h-8 text-success-600 mx-auto mb-2" />
                <p class="text-center text-neutral-600 dark:text-neutral-400">
                    All settled up! 🎉
                </p>
            </div>
        </div>
    </Card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Card, Spinner, Alert } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import { settlementService } from '@/services/settlementService'
import type { UserFinancialSummary } from '@/types/expense'

const props = defineProps<{
    groupId?: number
}>()

// State
const summary = ref<UserFinancialSummary | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)

// Computed
const balanceColorClass = computed(() => {
    if (!summary.value) return 'text-neutral-900'
    if (summary.value.net_balance > 0) return 'text-success-600'
    if (summary.value.net_balance < 0) return 'text-error-600'
    return 'text-neutral-900'
})

// Methods
function formatCurrency(amount: number, currency: string) {
    try {
        return new Intl.NumberFormat(undefined, {
            style: 'currency',
            currency
        }).format(amount)
    } catch {
        return `${amount.toFixed(2)} ${currency}`
    }
}

function getBalanceStatusText(balance: number) {
    if (balance > 0) return "You are owed money"
    if (balance < 0) return "You owe money"
    return "You are all settled up"
}

async function loadSummary() {
    loading.value = true
    error.value = null

    try {
        if (props.groupId) {
            summary.value = await settlementService.getGroupFinancialSummary(props.groupId)
        } else {
            summary.value = await settlementService.getUserFinancialSummary()
        }
    } catch (err: any) {
        error.value = err.response?.data?.detail || 'Failed to load financial summary'
    } finally {
        loading.value = false
    }
}

// Lifecycle
onMounted(() => {
    loadSummary()
})

watch(() => props.groupId, () => {
    loadSummary()
})
</script>

<style scoped>
.financial-summary-card {
    @apply p-6;
}

.summary-header {
    @apply mb-6;
}

.summary-title {
    @apply text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-1;
}

.summary-subtitle {
    @apply text-sm text-neutral-600 dark:text-neutral-400;
}

.summary-loading {
    @apply py-8 text-center;
}

.summary-content {
    @apply space-y-6;
}

.net-balance-section {
    @apply text-center py-4 border-b border-neutral-200 dark:border-neutral-700;
}

.balance-amount {
    @apply text-3xl font-bold mb-1;
}

.balance-status {
    @apply text-sm font-medium text-neutral-600 dark:text-neutral-400;
}

.spending-section {
    @apply flex justify-between items-center py-2;
}

.spending-label {
    @apply text-sm text-neutral-600 dark:text-neutral-400;
}

.spending-amount {
    @apply text-lg font-semibold text-neutral-900 dark:text-neutral-100;
}

.debts-credits-section {
    @apply space-y-4;
}

.section-title {
    @apply text-sm font-semibold text-neutral-700 dark:text-neutral-300 mb-2;
}

.debt-credit-list {
    @apply space-y-2;
}

.debt-credit-item {
    @apply flex justify-between items-center p-3 rounded-lg;
}

.debt-credit-item.debt {
    @apply bg-error-50 dark:bg-error-900/20;
}

.debt-credit-item.credit {
    @apply bg-success-50 dark:bg-success-900/20;
}

.user-info {
    @apply flex items-center;
}

.user-name {
    @apply font-medium text-neutral-900 dark:text-neutral-100;
}

.amount {
    @apply font-semibold;
}

.amount-debt {
    @apply text-error-600 dark:text-error-400;
}

.amount-credit {
    @apply text-success-600 dark:text-success-400;
}

.all-settled {
    @apply text-center py-8;
}
</style>