<template>
    <Dialog :model-value="modelValue" size="lg" @update:model-value="$emit('update:modelValue', false)">
        <template #header>
            <h2 class="text-xl font-semibold">{{ expense?.description || 'Expense Details' }}</h2>
        </template>

        <template #default>
            <div v-if="expense" class="space-y-6">
                <!-- Expense Overview -->
                <div class="bg-neutral-50 dark:bg-neutral-800 rounded-lg p-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-neutral-600 dark:text-neutral-400">Total Amount</p>
                            <p class="text-lg font-semibold">{{ formatCurrency(parseFloat(expense.total_amount),
                                expense.currency) }}</p>
                        </div>
                        <div>
                            <p class="text-sm text-neutral-600 dark:text-neutral-400">Split Type</p>
                            <p class="text-sm font-medium capitalize">{{ expense.split_type.toLowerCase().replace('_', '
                                ') }}</p>
                        </div>
                        <div>
                            <p class="text-sm text-neutral-600 dark:text-neutral-400">Paid By</p>
                            <p class="text-sm font-medium">{{ expense.paid_by_user?.name || expense.paid_by_user?.email
                                || `User #${expense.paid_by_user_id}` }}</p>
                        </div>
                        <div>
                            <p class="text-sm text-neutral-600 dark:text-neutral-400">Date</p>
                            <p class="text-sm font-medium">{{ formatDate(expense.expense_date) }}</p>
                        </div>
                    </div>
                </div>

                <!-- Expense Splits -->
                <div class="space-y-4">
                    <h3 class="text-lg font-semibold">Expense Splits</h3>
                    <div class="space-y-3">
                        <div v-for="split in expense.splits" :key="split.id"
                            class="border border-neutral-200 dark:border-neutral-700 rounded-lg p-4">
                            <div class="flex items-center justify-between mb-3">
                                <div>
                                    <p class="font-medium">{{ split.user?.name || split.user?.email || `User
                                        #${split.user_id}` }}</p>
                                    <p class="text-sm text-neutral-600 dark:text-neutral-400">
                                        Owes {{ formatCurrency(parseFloat(split.owed_amount), expense.currency) }}
                                    </p>
                                </div>
                                <div class="text-right">
                                    <span
                                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                        :class="getStatusColor(split.status)">
                                        {{ split.status.replace('_', ' ') }}
                                    </span>
                                    <p v-if="remaining(split) > 0" class="text-xs text-error mt-1">
                                        {{ formatCurrency(remaining(split), expense.currency) }} remaining
                                    </p>
                                </div>
                            </div>

                            <!-- Settlement Activities for this split -->
                            <div v-if="split.settlement_activities && split.settlement_activities.length > 0"
                                class="mt-3 pt-3 border-t border-neutral-100 dark:border-neutral-600">
                                <p class="text-sm font-medium mb-2">Payment History</p>
                                <div class="space-y-2">
                                    <div v-for="activity in split.settlement_activities" :key="activity.id"
                                        class="flex items-center justify-between text-sm bg-neutral-100 dark:bg-neutral-700 rounded p-2">
                                        <span>{{ formatCurrency(parseFloat(activity.amount_paid), expense.currency) }}
                                            paid</span>
                                        <span class="text-neutral-500">{{ formatDate(activity.paid_at) }}</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Settlement Action -->
                            <div v-if="canSettle(split)"
                                class="mt-3 pt-3 border-t border-neutral-100 dark:border-neutral-600">
                                <Button variant="solid" size="sm" @click="settleSplit(split)">
                                    Settle {{ formatCurrency(remaining(split), expense.currency) }}
                                </Button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </template>

        <template #footer>
            <div class="flex justify-between">
                <Button v-if="canEdit" variant="ghost" @click="editExpense">
                    Edit Expense
                </Button>
                <div></div>
                <Button variant="solid" @click="$emit('update:modelValue', false)">
                    Close
                </Button>
            </div>
        </template>
    </Dialog>
</template>

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

const props = defineProps<{
    modelValue: boolean
    expense: Expense | null
}>()

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

const authStore = useAuthStore()

// Computed
const canEdit = computed(() => {
    if (!props.expense || !authStore.user) return false
    return props.expense.paid_by_user_id === authStore.user.id ||
        props.expense.created_by_user_id === authStore.user.id
})

// 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 formatDate(dateString: string) {
    try {
        return format(new Date(dateString), 'MMM d, yyyy')
    } catch {
        return dateString
    }
}

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

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

function getStatusColor(status: string) {
    switch (status) {
        case 'paid':
            return 'bg-success-100 text-success-800 dark:bg-success-900 dark:text-success-200'
        case 'partially_paid':
            return 'bg-warning-100 text-warning-800 dark:bg-warning-900 dark:text-warning-200'
        default:
            return 'bg-neutral-100 text-neutral-800 dark:bg-neutral-700 dark:text-neutral-200'
    }
}

function settleSplit(split: ExpenseSplit) {
    if (props.expense) {
        emit('settle', { split, expense: props.expense })
    }
}

function editExpense() {
    if (props.expense) {
        emit('edit', props.expense)
    }
}
</script>

<style scoped>
/* Additional component-specific styles if needed */
</style>