<template>
    <ul class="space-y-2">
        <li v-for="expense in expenses" :key="expense.id" class="p-4 rounded bg-white dark:bg-neutral-800 shadow-sm">
            <div class="flex items-start gap-3">
                <div class="flex-1 cursor-pointer" @click="toggle(expense.id)">
                    <p class="font-medium leading-tight">{{ expense.description }}</p>
                    <p class="text-xs text-neutral-500 mt-0.5">
                        {{ $t('expenseList.paidBy', 'Paid by') }}
                        {{ expense.paid_by_user?.full_name || expense.paid_by_user?.email || '#' +
                            expense.paid_by_user_id
                        }} ·
                        {{ formatCurrency(parseFloat(expense.total_amount), expense.currency) }}
                    </p>
                </div>
                <div class="flex items-center gap-1 ml-auto">
                    <Button variant="ghost" size="sm" @click.stop="$emit('edit', expense)">
                        <BaseIcon name="heroicons:pencil-square-20-solid" class="w-4 h-4" />
                    </Button>
                    <Button variant="ghost" size="sm" color="danger" @click.stop="$emit('delete', expense)">
                        <BaseIcon name="heroicons:trash-20-solid" class="w-4 h-4" />
                    </Button>
                </div>
            </div>

            <!-- Details -->
            <div v-if="expandedId === expense.id"
                class="mt-2 pt-2 border-t border-neutral-200 dark:border-neutral-700 space-y-1">
                <div v-for="split in expense.splits" :key="split.id" class="space-y-2">
                    <div class="flex items-center text-sm gap-2 flex-wrap">
                        <span class="text-neutral-600 dark:text-neutral-300">{{ split.user?.full_name ||
                            split.user?.email
                            || 'User #' + split.user_id }} owes</span>
                        <span class="font-mono font-semibold">{{ formatCurrency(parseFloat(split.owed_amount),
                            expense.currency) }}</span>
                        <span v-if="remaining(split) > 0" class="text-xs text-error">{{
                            formatCurrency(remaining(split),
                                expense.currency) }} {{ $t('expenseList.remaining', 'left') }}</span>
                        <Button v-if="canSettle(split)" variant="solid" size="sm" class="ml-auto"
                            @click.stop="$emit('settle', { split, expense })">
                            {{ $t('expenseList.settle', 'Settle') }}
                        </Button>
                    </div>

                    <!-- Settlement History -->
                    <div v-if="split.settlement_activities && split.settlement_activities.length > 0"
                        class="ml-4 space-y-1">
                        <p class="text-xs text-neutral-500 font-medium">Payment History</p>
                        <div v-for="activity in split.settlement_activities" :key="activity.id"
                            class="flex items-center justify-between text-xs text-neutral-600 dark:text-neutral-400 bg-neutral-50 dark:bg-neutral-800 rounded px-2 py-1">
                            <span>{{ formatCurrency(parseFloat(activity.amount_paid), expense.currency) }} paid</span>
                            <span>{{ formatDate(activity.paid_at) }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </li>
    </ul>
</template>

<script setup lang="ts">
import { ref, computed, type PropType } from 'vue'
import BaseIcon from '@/components/BaseIcon.vue'
import { Button } from '@/components/ui'
import type { Expense, ExpenseSplit } from '@/types/expense'
import { useAuthStore } from '@/stores/auth'
import { format } from 'date-fns'

defineProps({
    expenses: {
        type: Array as PropType<Expense[]>,
        required: true,
    },
})

const emit = defineEmits<{
    (e: 'edit', expense: Expense): void
    (e: 'delete', expense: Expense): void
    (e: 'settle', payload: { split: ExpenseSplit; expense: Expense }): void
}>()

const expandedId = ref<number | null>(null)
function toggle(id: number) {
    expandedId.value = expandedId.value === id ? null : id
}

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

function remaining(split: ExpenseSplit) {
    const paid = split.settlement_activities.reduce((s, a) => s + parseFloat(a.amount_paid), 0)
    return parseFloat(split.owed_amount) - paid
}

const authStore = useAuthStore()
function canSettle(split: ExpenseSplit) {
    return authStore.getUser && authStore.getUser.id === split.user_id && remaining(split) > 0
}

function formatDate(dateString: string) {
    try {
        return format(new Date(dateString), 'MMM d, HH:mm')
    } catch {
        return dateString
    }
}
</script>

<style scoped>
/* Tailwind covers layout */
</style>