let allExpenses = [];

document.addEventListener('DOMContentLoaded', async () => {
    document.getElementById('expenseDate').valueAsDate = new Date();

    // Set default summary dates (current month)
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    document.getElementById('summaryStartDate').valueAsDate = firstDay;
    document.getElementById('summaryEndDate').valueAsDate = today;

    await loadExpenses();
    updateSummary();
});

async function loadExpenses(filters = {}) {
    try {
        let url = '/expenses';
        const params = new URLSearchParams();

        if (filters.start_date) params.append('start_date', filters.start_date);
        if (filters.end_date) params.append('end_date', filters.end_date);
        if (filters.category) params.append('category', filters.category);

        if (params.toString()) url += '?' + params.toString();

        allExpenses = await app.apiGet(url);
        displayExpenses();
    } catch (error) {
        console.error('Error loading expenses:', error);
        document.getElementById('expenseTableBody').innerHTML =
            '<tr><td colspan="4" class="loading">Failed to load expenses</td></tr>';
    }
}

function displayExpenses() {
    const tbody = document.getElementById('expenseTableBody');

    if (allExpenses.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" class="loading">No expenses found</td></tr>';
        document.getElementById('totalExpenses').textContent = 'PKR 0';
        document.getElementById('footerTotal').textContent = 'PKR 0';
        return;
    }

    const total = allExpenses.reduce((sum, expense) => sum + expense.amount, 0);

    tbody.innerHTML = allExpenses.map(expense => `
        <tr class="fade-in">
            <td>${app.formatDate(expense.expense_date)}</td>
            <td><span class="badge" style="background: var(--bg-tertiary);">${expense.category}</span></td>
            <td>${expense.description}</td>
            <td class="text-danger"><strong>${app.formatCurrency(expense.amount)}</strong></td>
            <td>
                <button class="btn btn-danger" onclick="deleteExpense(${expense.id})" style="padding: 0.25rem 0.75rem; font-size: 0.75rem;">
                    Delete
                </button>
            </td>
        </tr>
    `).join('');

    // Update totals
    document.getElementById('totalExpenses').textContent = app.formatCurrency(total);
    document.getElementById('footerTotal').textContent = app.formatCurrency(total);
}

async function deleteExpense(id) {
    if (confirm('Are you sure you want to delete this expense?')) {
        try {
            await app.apiDelete(`/expenses/${id}`);
            app.showNotification('Expense deleted successfully', 'success');
            await loadExpenses();
            updateSummary();
        } catch (error) {
            console.error('Error deleting expense:', error);
            app.showNotification('Failed to delete expense', 'error');
        }
    }
}

async function addExpense(event) {
    event.preventDefault();

    const expenseData = {
        expense_date: document.getElementById('expenseDate').value,
        category: document.getElementById('expenseCategory').value,
        description: document.getElementById('expenseDescription').value,
        amount: parseFloat(document.getElementById('expenseAmount').value)
    };

    try {
        await app.apiPost('/expenses', expenseData);
        app.showNotification('Expense added successfully', 'success');

        // Reset form
        document.getElementById('expenseForm').reset();
        document.getElementById('expenseDate').valueAsDate = new Date();

        // Reload expenses
        await loadExpenses();
        updateSummary();
    } catch (error) {
        console.error('Error adding expense:', error);
        app.showNotification('Failed to add expense', 'error');
    }
}

function filterExpenses() {
    const filters = {
        start_date: document.getElementById('filterStartDate').value,
        end_date: document.getElementById('filterEndDate').value,
        category: document.getElementById('filterCategory').value
    };
    loadExpenses(filters);
}

function clearExpenseFilters() {
    document.getElementById('filterStartDate').value = '';
    document.getElementById('filterEndDate').value = '';
    document.getElementById('filterCategory').value = '';
    loadExpenses();
}

async function updateSummary() {
    const startDate = document.getElementById('summaryStartDate').value;
    const endDate = document.getElementById('summaryEndDate').value;

    try {
        let url = '/expenses';
        const params = new URLSearchParams();
        if (startDate) params.append('start_date', startDate);
        if (endDate) params.append('end_date', endDate);
        if (params.toString()) url += '?' + params.toString();

        const expenses = await app.apiGet(url);

        // Group by category
        const categoryTotals = {};
        expenses.forEach(expense => {
            if (!categoryTotals[expense.category]) {
                categoryTotals[expense.category] = 0;
            }
            categoryTotals[expense.category] += expense.amount;
        });

        const total = Object.values(categoryTotals).reduce((sum, val) => sum + val, 0);

        const summaryContainer = document.getElementById('expenseSummary');

        if (Object.keys(categoryTotals).length === 0) {
            summaryContainer.innerHTML = '<p class="loading">No expenses in selected period</p>';
            return;
        }

        summaryContainer.innerHTML = `
            <div style="background: var(--bg-tertiary); border-radius: var(--radius-md); padding: 1rem;">
                ${Object.entries(categoryTotals).map(([category, amount]) => `
                    <div style="display: flex; justify-content: space-between; padding: 0.75rem 0; border-bottom: 1px solid var(--glass-border);">
                        <span style="color: var(--text-secondary);">${category}</span>
                        <strong style="color: var(--text-primary);">${app.formatCurrency(amount)}</strong>
                    </div>
                `).join('')}
                <div style="display: flex; justify-content: space-between; padding: 1rem 0; margin-top: 0.5rem;">
                    <span style="font-size: 1.125rem; font-weight: 600; color: var(--text-primary);">Total</span>
                    <strong style="font-size: 1.5rem; color: var(--danger);">${app.formatCurrency(total)}</strong>
                </div>
            </div>
        `;
    } catch (error) {
        console.error('Error updating summary:', error);
        document.getElementById('expenseSummary').innerHTML = '<p class="loading">Failed to load summary</p>';
    }
}
