// Dashboard Page
let incomeExpenseChart = null;
let paymentMethodChart = null;

async function renderDashboard() {
    const content = document.getElementById('main-content');
    
    try {
        const data = await apiRequest(`dashboard.php?startDate=${currentDateFilter.startDate}&endDate=${currentDateFilter.endDate}`);
        
        content.innerHTML = `
            ${renderDateFilter()}
            
            <!-- Stats Cards -->
            <div class="grid-stats mb-6">
                <div class="card stats-card" data-testid="card-total-income">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400">Total Entradas</span>
                        <svg class="w-5 h-5 text-income" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 11l5-5m0 0l5 5m-5-5v12"/></svg>
                    </div>
                    <div class="text-2xl font-bold text-income">${formatMoney(data.totalIncome)}</div>
                </div>
                
                <div class="card stats-card" data-testid="card-total-expenses">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400">Total Saídas</span>
                        <svg class="w-5 h-5 text-expense" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 13l-5 5m0 0l-5-5m5 5V6"/></svg>
                    </div>
                    <div class="text-2xl font-bold text-expense">${formatMoney(data.totalExpenses)}</div>
                </div>
                
                <div class="card stats-card" data-testid="card-balance">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400">Saldo</span>
                        <svg class="w-5 h-5 ${data.balance >= 0 ? 'text-income' : 'text-expense'}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    </div>
                    <div class="text-2xl font-bold ${data.balance >= 0 ? 'text-income' : 'text-expense'}">${formatMoney(data.balance)}</div>
                </div>
                
                <div class="card stats-card" data-testid="card-pending-bills">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400">Boletos Pendentes</span>
                        <svg class="w-5 h-5 text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    </div>
                    <div class="text-2xl font-bold text-gray-800 dark:text-white">${data.pendingBills}</div>
                </div>
                
                <div class="card stats-card" data-testid="card-overdue-bills">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400">Boletos Vencidos</span>
                        <svg class="w-5 h-5 text-expense" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
                    </div>
                    <div class="text-2xl font-bold text-expense">${data.overdueBills}</div>
                </div>
                
                <div class="card stats-card" data-testid="card-partner-loans">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400">Empréstimos Parceiros</span>
                        <svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                    </div>
                    <div class="text-2xl font-bold text-blue-500">${formatMoney(data.partnerLoans)}</div>
                </div>
            </div>
            
            <!-- Charts -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="card">
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Entradas x Saídas por Mês</h3>
                    <div class="chart-container">
                        <canvas id="income-expense-chart"></canvas>
                    </div>
                </div>
                
                <div class="card">
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Vendas por Forma de Pagamento</h3>
                    <div class="chart-container">
                        <canvas id="payment-method-chart"></canvas>
                    </div>
                </div>
            </div>
        `;
        
        // Render charts
        renderIncomeExpenseChart(data.monthlyData);
        renderPaymentMethodChart(data.incomeByPaymentMethod);
        
    } catch (error) {
        content.innerHTML = `<div class="empty-state"><p>Erro ao carregar dashboard: ${error.message}</p></div>`;
    }
}

function renderIncomeExpenseChart(monthlyData) {
    const ctx = document.getElementById('income-expense-chart');
    if (!ctx) return;
    
    if (incomeExpenseChart) {
        incomeExpenseChart.destroy();
    }
    
    incomeExpenseChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: monthlyData.map(d => d.month),
            datasets: [
                {
                    label: 'Entradas',
                    data: monthlyData.map(d => d.income),
                    backgroundColor: '#22c55e',
                    borderRadius: 4
                },
                {
                    label: 'Saídas',
                    data: monthlyData.map(d => d.expense),
                    backgroundColor: '#ef4444',
                    borderRadius: 4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: value => formatMoney(value)
                    }
                }
            }
        }
    });
}

function renderPaymentMethodChart(paymentMethodData) {
    const ctx = document.getElementById('payment-method-chart');
    if (!ctx) return;
    
    if (paymentMethodChart) {
        paymentMethodChart.destroy();
    }
    
    const labels = {
        cash: 'Dinheiro',
        debit: 'Débito',
        credit: 'Crédito',
        pix: 'PIX',
        ifood: 'iFood'
    };
    
    const colors = {
        cash: '#22c55e',
        debit: '#3b82f6',
        credit: '#8b5cf6',
        pix: '#06b6d4',
        ifood: '#ef4444'
    };
    
    const data = Object.entries(paymentMethodData);
    
    if (data.length === 0) {
        ctx.parentElement.innerHTML = '<div class="empty-state"><p>Sem dados de pagamento</p></div>';
        return;
    }
    
    paymentMethodChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: data.map(([key]) => labels[key] || key),
            datasets: [{
                data: data.map(([, value]) => value),
                backgroundColor: data.map(([key]) => colors[key] || '#6b7280')
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: (context) => formatMoney(context.raw)
                    }
                }
            }
        }
    });
}
