<template>
    <section class="neo-expenses-section">
        <VCard v-if="isLoading && expenses.length === 0" class="py-10 text-center">
            <VSpinner :label="$t('listDetailPage.expensesSection.loading')" size="lg" />
        </VCard>
        <VAlert v-else-if="error && expenses.length === 0" type="error" class="mt-4">
            <p>{{ error }}</p>
            <template #actions>
                <VButton @click="$emit('retry-fetch')">
                    {{ $t('listDetailPage.expensesSection.retryButton') }}
                </VButton>
            </template>
        </VAlert>
        <VCard v-else-if="(!expenses || expenses.length === 0) && !isLoading" variant="empty-state" empty-icon="receipt"
            :empty-title="$t('listDetailPage.expensesSection.emptyStateTitle')"
            :empty-message="$t('listDetailPage.expensesSection.emptyStateMessage')" class="mt-4">
        </VCard>
        <div v-else class="neo-expense-list">
            <div v-for="expense in expenses" :key="expense.id" class="neo-expense-item-wrapper">
                <div class="neo-expense-item" @click="toggleExpense(expense.id)"
                    :class="{ 'is-expanded': isExpenseExpanded(expense.id) }">
                    <div class="expense-main-content">
                        <div class="expense-icon-container">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round">
                                <line x1="12" x2="12" y1="2" y2="22"></line>
                                <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
                            </svg>
                        </div>
                        <div class="expense-text-content">
                            <div class="neo-expense-header">
                                {{ expense.description }}
                            </div>
                            <div class="neo-expense-details">
                                {{ formatCurrency(expense.total_amount) }} &mdash;
                                {{ $t('listDetailPage.expensesSection.paidBy') }} <strong>{{ expense.paid_by_user?.name
                                    ||
                                    expense.paid_by_user?.email }}</strong>
                            </div>
                        </div>
                    </div>
                    <div class="expense-side-content">
                        <span class="neo-expense-status" :class="getStatusClass(expense.overall_settlement_status)">
                            {{ getOverallExpenseStatusText(expense.overall_settlement_status) }}
                        </span>
                        <div class="expense-toggle-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round" class="feather feather-chevron-down">
                                <polyline points="6 9 12 15 18 9"></polyline>
                            </svg>
                        </div>
                    </div>
                </div>

                <!-- Collapsible content -->
                <div v-if="isExpenseExpanded(expense.id)" class="neo-splits-container">
                    <div class="neo-splits-list">
                        <div v-for="split in expense.splits" :key="split.id" class="neo-split-item">
                            <div class="split-col split-user">
                                <strong>{{ split.user?.name || split.user?.email || `User ID: ${split.user_id}`
                                }}</strong>
                            </div>
                            <div class="split-col split-owes">
                                {{ $t('listDetailPage.expensesSection.owes') }} <strong>{{
                                    formatCurrency(split.owed_amount) }}</strong>
                            </div>
                            <div class="split-col split-status">
                                <span class="neo-expense-status" :class="getStatusClass(split.status)">
                                    {{ getSplitStatusText(split.status) }}
                                </span>
                            </div>
                            <div class="split-col split-paid-info">
                                <div v-if="split.paid_at" class="paid-details">
                                    {{ $t('listDetailPage.expensesSection.paidAmount') }} {{
                                        getPaidAmountForSplitDisplay(split)
                                    }}
                                    <span v-if="split.paid_at"> {{ $t('listDetailPage.expensesSection.onDate') }} {{ new
                                        Date(split.paid_at).toLocaleDateString() }}</span>
                                </div>
                            </div>
                            <div class="split-col split-action">
                                <button
                                    v-if="split.user_id === currentUserId && split.status !== ExpenseSplitStatusEnum.PAID"
                                    class="btn btn-sm btn-primary" @click="$emit('settle-share', expense, split)"
                                    :disabled="isSettlementLoading">
                                    {{ $t('listDetailPage.expensesSection.settleShareButton') }}
                                </button>
                            </div>
                            <ul v-if="split.settlement_activities && split.settlement_activities.length > 0"
                                class="neo-settlement-activities">
                                <li v-for="activity in split.settlement_activities" :key="activity.id">
                                    {{ $t('listDetailPage.expensesSection.activityLabel') }} {{
                                        formatCurrency(activity.amount_paid) }}
                                    {{
                                        $t('listDetailPage.expensesSection.byUser') }} {{ activity.payer?.name || `User
                                    ${activity.paid_by_user_id}` }} {{ $t('listDetailPage.expensesSection.onDate') }} {{
                                        new
                                            Date(activity.paid_at).toLocaleDateString() }}
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue';
import type { PropType } from 'vue';
import { useI18n } from 'vue-i18n';
import type { Expense, ExpenseSplit } from '@/types/expense';
import { ExpenseOverallStatusEnum, ExpenseSplitStatusEnum } from '@/types/expense';
import { useListDetailStore } from '@/stores/listDetailStore';
import VCard from '@/components/valerie/VCard.vue';
import VSpinner from '@/components/valerie/VSpinner.vue';
import VAlert from '@/components/valerie/VAlert.vue';
import VButton from '@/components/valerie/VButton.vue';

const props = defineProps({
    expenses: {
        type: Array as PropType<Expense[]>,
        required: true,
    },
    isLoading: {
        type: Boolean,
        default: false,
    },
    error: {
        type: String as PropType<string | null>,
        default: null,
    },
    currentUserId: {
        type: Number as PropType<number | null>,
        required: true,
    },
    isSettlementLoading: {
        type: Boolean,
        default: false,
    }
});

defineEmits(['retry-fetch', 'settle-share']);

const { t } = useI18n();
const listDetailStore = useListDetailStore();

const expandedExpenses = ref<Set<number>>(new Set());

const toggleExpense = (expenseId: number) => {
    const newSet = new Set(expandedExpenses.value);
    if (newSet.has(expenseId)) {
        newSet.delete(expenseId);
    } else {
        newSet.add(expenseId);
    }
    expandedExpenses.value = newSet;
};

const isExpenseExpanded = (expenseId: number) => {
    return expandedExpenses.value.has(expenseId);
};

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)}`;
};

const getPaidAmountForSplitDisplay = (split: ExpenseSplit): string => {
    const amount = listDetailStore.getPaidAmountForSplit(split.id);
    return formatCurrency(amount);
};

const getSplitStatusText = (status: ExpenseSplitStatusEnum): string => {
    switch (status) {
        case ExpenseSplitStatusEnum.PAID: return t('listDetailPage.status.paid');
        case ExpenseSplitStatusEnum.PARTIALLY_PAID: return t('listDetailPage.status.partiallyPaid');
        case ExpenseSplitStatusEnum.UNPAID: return t('listDetailPage.status.unpaid');
        default: return t('listDetailPage.status.unknown');
    }
};

const getOverallExpenseStatusText = (status: ExpenseOverallStatusEnum): string => {
    switch (status) {
        case ExpenseOverallStatusEnum.PAID: return t('listDetailPage.status.settled');
        case ExpenseOverallStatusEnum.PARTIALLY_PAID: return t('listDetailPage.status.partiallySettled');
        case ExpenseOverallStatusEnum.UNPAID: return t('listDetailPage.status.unsettled');
        default: return t('listDetailPage.status.unknown');
    }
};

const getStatusClass = (status: ExpenseSplitStatusEnum | ExpenseOverallStatusEnum): string => {
    if (status === ExpenseSplitStatusEnum.PAID || status === ExpenseOverallStatusEnum.PAID) return 'status-paid';
    if (status === ExpenseSplitStatusEnum.PARTIALLY_PAID || status === ExpenseOverallStatusEnum.PARTIALLY_PAID) return 'status-partially_paid';
    if (status === ExpenseSplitStatusEnum.UNPAID || status === ExpenseOverallStatusEnum.UNPAID) return 'status-unpaid';
    return '';
};
</script>

<style scoped>
.neo-expenses-section {
    padding: 0;
    margin-top: 1.2rem;
}

.neo-expense-list {
    background-color: rgb(255, 248, 240);
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid #f0e5d8;
}

.neo-expense-item-wrapper {
    border-bottom: 1px solid #f0e5d8;
}

.neo-expense-item-wrapper:last-child {
    border-bottom: none;
}

.neo-expense-item {
    padding: 1rem 1.2rem;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: background-color 0.2s ease;
}

.neo-expense-item:hover {
    background-color: rgba(0, 0, 0, 0.02);
}

.neo-expense-item.is-expanded .expense-toggle-icon {
    transform: rotate(180deg);
}

.expense-main-content {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.expense-icon-container {
    color: #d99a53;
}

.expense-text-content {
    display: flex;
    flex-direction: column;
}

.expense-side-content {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.expense-toggle-icon {
    color: #888;
    transition: transform 0.3s ease;
}

.neo-expense-header {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 0.1rem;
}

.neo-expense-details,
.neo-split-details {
    font-size: 0.9rem;
    color: #555;
    margin-bottom: 0.3rem;
}

.neo-expense-details strong,
.neo-split-details strong {
    color: #111;
}

.neo-expense-status {
    display: inline-block;
    padding: 0.25em 0.6em;
    font-size: 0.85em;
    font-weight: 700;
    line-height: 1;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 0.375rem;
    margin-left: 0.5rem;
    color: #22c55e;
}

.status-unpaid {
    background-color: #fee2e2;
    color: #dc2626;
}

.status-partially_paid {
    background-color: #ffedd5;
    color: #f97316;
}

.status-paid {
    background-color: #dcfce7;
    color: #22c55e;
}

.neo-splits-container {
    padding: 0.5rem 1.2rem 1.2rem;
    background-color: rgba(255, 255, 255, 0.5);
}

.neo-splits-list {
    margin-top: 0rem;
    padding-left: 0;
    border-left: none;
}

.neo-split-item {
    padding: 0.75rem 0;
    border-bottom: 1px dashed #f0e5d8;
    display: grid;
    grid-template-areas:
        "user owes status paid action"
        "activities activities activities activities activities";
    grid-template-columns: 1.5fr 1fr 1fr 1.5fr auto;
    gap: 0.5rem 1rem;
    align-items: center;
}

.neo-split-item:last-child {
    border-bottom: none;
}

.split-col.split-user {
    grid-area: user;
}

.split-col.split-owes {
    grid-area: owes;
}

.split-col.split-status {
    grid-area: status;
}

.split-col.split-paid-info {
    grid-area: paid;
}

.split-col.split-action {
    grid-area: action;
    justify-self: end;
}

.split-col.neo-settlement-activities {
    grid-area: activities;
    font-size: 0.8em;
    color: #555;
    padding-left: 1em;
    list-style-type: disc;
    margin-top: 0.5em;
}

.neo-settlement-activities {
    font-size: 0.8em;
    color: #555;
    padding-left: 1em;
    list-style-type: disc;
    margin-top: 0.5em;
}

.neo-settlement-activities li {
    margin-top: 0.2em;
}
</style>