<template>
    <main class="p-4 max-w-screen-lg mx-auto space-y-6">
        <!-- Header -->
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-neutral-900 dark:text-neutral-100">
                    {{ $t('settlementsPage.title', 'Settlements') }}
                </h1>
                <p class="text-sm text-neutral-600 dark:text-neutral-400">
                    {{ $t('settlementsPage.subtitle', 'Manage payments and settle debts') }}
                </p>
            </div>
            <Button v-if="groupId" variant="solid" @click="showCreateSettlement = true">
                <BaseIcon name="heroicons:plus-20-solid" class="w-5 h-5 mr-1" />
                {{ $t('settlementsPage.recordSettlement', 'Record Settlement') }}
            </Button>
        </div>

        <!-- Filter Tabs -->
        <Tabs v-model="activeTab" :tabs="tabs" />

        <!-- Content based on active tab -->
        <div class="tab-content">
            <!-- Settlement History Tab -->
            <div v-if="activeTab === 'history'" class="space-y-4">
                <Spinner v-if="loading" :label="$t('settlementsPage.loadingSettlements', 'Loading settlements')" />
                <Alert v-else-if="error" type="error" :message="error" />
                <div v-else-if="settlements.length === 0" class="text-center py-8">
                    <BaseIcon name="heroicons:currency-dollar-solid" class="w-12 h-12 mx-auto text-neutral-400 mb-4" />
                    <p class="text-neutral-500">{{ $t('settlementsPage.noSettlements', 'No settlements found') }}</p>
                </div>
                <div v-else class="space-y-3">
                    <SettlementCard v-for="settlement in settlements" :key="settlement.id" :settlement="settlement"
                        @edit="editSettlement" @delete="confirmDeleteSettlement" />
                </div>
            </div>

            <!-- Summary Tab -->
            <div v-if="activeTab === 'summary'" class="space-y-4">
                <FinancialSummaryCard :group-id="groupId" />
            </div>

            <!-- Suggested Settlements Tab -->
            <div v-if="activeTab === 'suggested'" class="space-y-4">
                <SuggestedSettlementsCard :group-id="groupId" @settle="handleSuggestedSettle" />
            </div>
        </div>

        <!-- Settlement Creation Modal -->
        <Dialog v-model="showCreateSettlement" size="md">
            <SettlementForm :group-id="groupId" :settlement="editingSettlement" @close="closeSettlementForm"
                @saved="handleSettlementSaved" />
        </Dialog>
    </main>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { Button, Spinner, Alert, Tabs, Dialog } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import SettlementCard from '@/components/settlements/SettlementCard.vue'
import SettlementForm from '@/components/settlements/SettlementForm.vue'
import FinancialSummaryCard from '@/components/settlements/FinancialSummaryCard.vue'
import SuggestedSettlementsCard from '@/components/settlements/SuggestedSettlementsCard.vue'
import { settlementService } from '@/services/settlementService'
import { useNotificationStore } from '@/stores/notifications'
import type { Settlement } from '@/types/expense'

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

const route = useRoute()
const notifications = useNotificationStore()

// State
const settlements = ref<Settlement[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const showCreateSettlement = ref(false)
const editingSettlement = ref<Settlement | null>(null)
const activeTab = ref('history')

// Computed
const groupId = computed(() => {
    return props.groupId ? Number(props.groupId) :
        route.params.groupId ? Number(route.params.groupId) : undefined
})

const tabs = computed(() => [
    { id: 'history', name: 'Settlement History' },
    { id: 'summary', name: 'Financial Summary' },
    { id: 'suggested', name: 'Suggested Settlements' }
])

// Methods
async function loadSettlements() {
    if (!groupId.value) return

    loading.value = true
    error.value = null

    try {
        settlements.value = await settlementService.getGroupSettlements(groupId.value)
    } catch (err: any) {
        error.value = err.response?.data?.detail || 'Failed to load settlements'
    } finally {
        loading.value = false
    }
}

function editSettlement(settlement: Settlement) {
    editingSettlement.value = settlement
    showCreateSettlement.value = true
}

async function confirmDeleteSettlement(settlement: Settlement) {
    if (!confirm(`Delete settlement of ${settlement.amount} from ${settlement.payer?.name} to ${settlement.payee?.name}?`)) {
        return
    }

    try {
        await settlementService.deleteSettlement(settlement.id, settlement.version)
        await loadSettlements()
        notifications.addNotification({
            type: 'success',
            message: 'Settlement deleted successfully'
        })
    } catch (err: any) {
        notifications.addNotification({
            type: 'error',
            message: err.response?.data?.detail || 'Failed to delete settlement'
        })
    }
}

function closeSettlementForm() {
    showCreateSettlement.value = false
    editingSettlement.value = null
}

async function handleSettlementSaved() {
    closeSettlementForm()
    await loadSettlements()
}

function handleSuggestedSettle(suggestion: any) {
    // Pre-fill the settlement form with suggested values
    editingSettlement.value = {
        group_id: groupId.value!,
        paid_by_user_id: suggestion.from_user_id,
        paid_to_user_id: suggestion.to_user_id,
        amount: suggestion.amount,
        description: 'Suggested settlement'
    } as any
    showCreateSettlement.value = true
}

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

watch(() => groupId.value, () => {
    loadSettlements()
})
</script>

<style scoped>
.tab-content {
    min-height: 400px;
}
</style>