<template>
    <main class="p-4 max-w-screen-md mx-auto space-y-6">
        <!-- Overview -->
        <ExpenseOverview />

        <!-- Controls -->
        <div class="flex justify-end">
            <Button variant="solid" @click="showCreate = true">
                <BaseIcon name="heroicons:plus-20-solid" class="w-5 h-5 mr-1" />
                {{ $t('expensePage.addExpense', 'Add Expense') }}
            </Button>
        </div>

        <!-- Error & Loading -->
        <Spinner v-if="loading" :label="$t('expensePage.loading', 'Loading expenses')" />
        <Alert v-else-if="error" type="error" :message="error" />

        <!-- Expense List -->
        <ExpenseList v-else :expenses="expenses" @edit="openEdit" @delete="confirmDelete" @settle="openSettle" />

        <!-- Sheets -->
        <ExpenseCreationSheet v-model="showCreate" :expense="editingExpense" />
        <SettlementFlow v-model="showSettlement" :split="selectedSplit" :expense="selectedExpense" />
    </main>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useExpenses } from '@/composables/useExpenses'
import { Button, Spinner, Alert } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import ExpenseOverview from '@/components/expenses/ExpenseOverview.vue'
import ExpenseList from '@/components/expenses/ExpenseList.vue'
import ExpenseCreationSheet from '@/components/expenses/ExpenseCreationSheet.vue'
import SettlementFlow from '@/components/expenses/SettlementFlow.vue'
import type { Expense } from '@/types/expense'

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

const showCreate = ref(false)
const showSettlement = ref(false)
const editingExpense = ref<Expense | null>(null)
const selectedSplit = ref<any | null>(null)
const selectedExpense = ref<Expense | null>(null)

const { expenses, loading, error, fetchExpenses, deleteExpense } = useExpenses()

onMounted(() => {
    load()
})

watch(
    () => props.groupId,
    () => load(),
)

async function load() {
    await fetchExpenses({ group_id: props.groupId ? Number(props.groupId) : undefined })
}

function openEdit(expense: Expense) {
    editingExpense.value = expense
    showCreate.value = true
}

watch(showCreate, val => {
    if (!val) editingExpense.value = null
})

async function confirmDelete(expense: Expense) {
    if (confirm('Delete this expense?')) {
        await deleteExpense(expense.id)
    }
}

function toggleDetails(expense: Expense) {
    // TODO: open details expanded row or dialog
    console.debug('details', expense)
}

function openSettle(payload: { split: any; expense: Expense }) {
    selectedSplit.value = payload.split
    selectedExpense.value = payload.expense
    showSettlement.value = true
}
</script>

<style scoped></style>
