<template>
    <Dialog :model-value="modelValue" size="lg" @update:model-value="$emit('update:modelValue', false)">
        <template #header>
            <h2 class="text-xl font-semibold">{{ $t('listDetailPage.modals.costSummary.title') }}</h2>
        </template>
        <template #default>
            <div v-if="loading" class="text-center">
                <Spinner :label="$t('listDetailPage.loading.costSummary')" />
            </div>
            <Alert v-else-if="error" type="error" :message="error" />
            <div v-else-if="summary">
                <div class="mb-3 cost-overview">
                    <p><strong>{{ $t('listDetailPage.modals.costSummary.totalCostLabel') }}</strong> {{
                        formatCurrency(summary.total_list_cost) }}</p>
                    <p><strong>{{ $t('listDetailPage.modals.costSummary.equalShareLabel') }}</strong> {{
                        formatCurrency(summary.equal_share_per_user) }}</p>
                    <p><strong>{{ $t('listDetailPage.modals.costSummary.participantsLabel') }}</strong> {{
                        summary.num_participating_users }}</p>
                </div>
                <h4>{{ $t('listDetailPage.modals.costSummary.userBalancesHeader') }}</h4>
                <div class="table-container mt-2">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>{{ $t('listDetailPage.modals.costSummary.tableHeaders.user') }}</th>
                                <th class="text-right">{{
                                    $t('listDetailPage.modals.costSummary.tableHeaders.itemsAddedValue') }}</th>
                                <th class="text-right">{{ $t('listDetailPage.modals.costSummary.tableHeaders.amountDue')
                                }}</th>
                                <th class="text-right">{{ $t('listDetailPage.modals.costSummary.tableHeaders.balance')
                                }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="userShare in summary.user_balances" :key="userShare.user_id">
                                <td>{{ userShare.user_identifier }}</td>
                                <td class="text-right">{{ formatCurrency(userShare.items_added_value) }}</td>
                                <td class="text-right">{{ formatCurrency(userShare.amount_due) }}</td>
                                <td class="text-right">
                                    <span
                                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                        :class="parseFloat(String(userShare.balance)) >= 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
                                        {{ formatCurrency(userShare.balance) }}
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <p v-else>{{ $t('listDetailPage.modals.costSummary.emptyState') }}</p>
        </template>
        <template #footer>
            <div class="flex justify-between">
                <Button v-if="summary && !summary.expense_exists" variant="solid" @click="$emit('generate-expense')"
                    :disabled="loading">
                    {{ $t('listDetailPage.modals.costSummary.generateExpense', 'Generate Expense') }}
                </Button>
                <div></div>
                <Button variant="solid" @click="$emit('update:modelValue', false)">
                    {{ $t('listDetailPage.buttons.close') }}
                </Button>
            </div>
        </template>
    </Dialog>
</template>

<script setup lang="ts">
import { defineProps, defineEmits } from 'vue';
import type { PropType } from 'vue';
import { useI18n } from 'vue-i18n';
import { Dialog, Spinner, Alert, Button } from '@/components/ui';

interface UserCostShare {
    user_id: number;
    user_identifier: string;
    items_added_value: string | number;
    amount_due: string | number;
    balance: string | number;
}

interface ListCostSummaryData {
    list_id: number;
    list_name: string;
    total_list_cost: string | number;
    num_participating_users: number;
    equal_share_per_user: string | number;
    user_balances: UserCostShare[];
    expense_exists: boolean;
    expense_id?: number;
}

defineProps({
    modelValue: {
        type: Boolean,
        required: true,
    },
    summary: {
        type: Object as PropType<ListCostSummaryData | null>,
        default: null,
    },
    loading: {
        type: Boolean,
        default: false,
    },
    error: {
        type: String as PropType<string | null>,
        default: null,
    },
});

defineEmits(['update:modelValue', 'generate-expense']);

const { t } = useI18n();

const formatCurrency = (value: string | number | undefined | null): string => {
    if (value === undefined || value === null) return '$0.00';
    if (typeof value === 'string' && !value.trim()) return '$0.00';
    const numValue = typeof value === 'string' ? parseFloat(value) : value;
    return isNaN(numValue) ? '$0.00' : `$${numValue.toFixed(2)}`;
};
</script>

<style scoped>
.cost-overview p {
    margin-bottom: 0.5rem;
}

.table-container {
    overflow-x: auto;
}

.table {
    width: 100%;
    border-collapse: collapse;
}

.table th,
.table td {
    padding: 0.75rem;
    border-bottom: 1px solid #eee;
}

.table th {
    text-align: left;
    font-weight: 600;
    background-color: #f8f9fa;
}

.text-right {
    text-align: right;
}
</style>