/**
 * Sales — Plataforma Ganadera
 * Gestión de ventas de animales, productos y mercancía
 */
const Sales = {
    page: 1,
    chartInstance: null,

    async init() {
        this.bindEvents();
        await Promise.all([this.loadSales(), this.loadStats()]);
        this.renderChart();
    },

    bindEvents() {
        $('#saleSearch').on('input', App.debounce(() => { this.page = 1; this.loadSales(); }, 300));
        $('#saleFrom, #saleTo, #saleStatus').on('change', () => { this.page = 1; this.loadSales(); });
    },

    async loadSales() {
        let url = `/sales?page=${this.page}&per_page=20`;
        const search = $('#saleSearch').val();
        const from = $('#saleFrom').val();
        const to = $('#saleTo').val();
        const status = $('#saleStatus').val();
        if (search) url += `&search=${encodeURIComponent(search)}`;
        if (from) url += `&from_date=${from}`;
        if (to) url += `&to_date=${to}`;
        if (status) url += `&status=${status}`;

        try {
            const res = await API.get(url);
            this.renderSales(res.data || []);
            if (res.meta && res.meta.total) {
                App.renderPagination('#salesPagination', res.meta, (p) => {
                    this.page = p;
                    this.loadSales();
                });
            }
        } catch(e) {
            $('#salesBody').html('<tr><td colspan="7" class="text-center">Error al cargar ventas</td></tr>');
        }
    },

    renderSales(sales) {
        if (!sales.length) {
            $('#salesBody').html('<tr><td colspan="7" class="text-center text-muted"><div class="empty-state"><p>Sin ventas registradas</p><a href="/ventas/nueva" class="btn btn-primary btn-sm">Crear primera venta</a></div></td></tr>');
            return;
        }
        const html = sales.map(s => {
            const date = new Date(s.sale_date).toLocaleDateString('es-MX', { day: '2-digit', month: 'short', year: 'numeric' });
            const total = parseFloat(s.total || 0).toLocaleString('es-MX', {style:'currency', currency:'MXN'});
            const statusLabels = { paid: 'Pagada', pending: 'Pendiente', partial: 'Parcial', cancelled: 'Cancelada' };
            const statusLabel = statusLabels[s.payment_status] || s.payment_status || 'Pendiente';
            return `<tr>
                <td><strong>#${s.id}</strong></td>
                <td>${date}</td>
                <td>${s.client_name || '<span class="text-muted">Sin cliente</span>'}</td>
                <td><span class="chip chip-sm">${s.items_count || 0}</span></td>
                <td><strong style="color:var(--color-primary)">${total}</strong></td>
                <td><span class="sale-status sale-${s.payment_status || 'pending'}">${statusLabel}</span></td>
                <td>
                    <button class="btn btn-sm btn-ghost" onclick="Sales.viewDetail(${s.id})" title="Ver detalle">${Icons.eye(14)}</button>
                    <button class="btn btn-sm btn-ghost text-danger" onclick="Sales.deleteSale(${s.id})" title="Eliminar">${Icons.trash(14)}</button>
                </td>
            </tr>`;
        }).join('');
        $('#salesBody').html(html);
    },

    async loadStats() {
        try {
            const res = await API.get('/sales/stats');
            const data = res.data || {};
            const summary = data.summary || {};
            $('#statSalesTotal').text(summary.total_sales || 0);
            const rev = parseFloat(summary.total_revenue || 0).toLocaleString('es-MX', {style:'currency', currency:'MXN'});
            $('#statRevenue').text(rev);
            $('#statAnimals').text(summary.animals_sold || 0);
            $('#statClients').text(summary.total_clients || 0);

            // Animate stats
            document.querySelectorAll('.stat-card .stat-value').forEach(el => {
                el.style.opacity = '0';
                el.style.transform = 'translateY(8px)';
                setTimeout(() => {
                    el.style.transition = 'all 0.4s ease';
                    el.style.opacity = '1';
                    el.style.transform = 'translateY(0)';
                }, 150);
            });
        } catch(e) {}
    },

    async renderChart() {
        const ctx = document.getElementById('salesChart');
        if (!ctx || typeof Chart === 'undefined') return;

        try {
            // Get last 6 months of sales data
            const months = [];
            const now = new Date();
            for (let i = 5; i >= 0; i--) {
                const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
                months.push({
                    label: d.toLocaleDateString('es-MX', { month: 'short', year: '2-digit' }),
                    from: d.toISOString().split('T')[0],
                    to: new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().split('T')[0],
                });
            }

            const totals = [];
            for (const m of months) {
                try {
                    const res = await API.get(`/sales?from_date=${m.from}&to_date=${m.to}&per_page=1`);
                    totals.push((res.meta && res.meta.total) || 0);
                } catch(e) { totals.push(0); }
            }

            if (this.chartInstance) this.chartInstance.destroy();
            this.chartInstance = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: months.map(m => m.label),
                    datasets: [{
                        label: 'Ventas',
                        data: totals,
                        backgroundColor: 'rgba(4,120,87,0.2)',
                        borderColor: '#047857',
                        borderWidth: 2,
                        borderRadius: 6,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        y: { beginAtZero: true, ticks: { precision: 0 } },
                        x: { grid: { display: false } }
                    },
                    animation: { duration: 800, easing: 'easeOutQuart' }
                }
            });
        } catch(e) {}
    },

    async viewDetail(id) {
        try {
            const res = await API.get(`/sales/${id}`);
            const s = res.data;
            const items = s.items || [];
            const total = parseFloat(s.total || 0).toLocaleString('es-MX', {style:'currency', currency:'MXN'});
            const statusLabels = { paid: 'Pagada', pending: 'Pendiente', partial: 'Parcial', cancelled: 'Cancelada' };

            let html = `<div class="sale-detail-header" style="margin-bottom:1.25rem">
                <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:0.75rem">
                    <div>
                        <h4 style="margin:0 0 0.25rem">Venta #${s.id}</h4>
                        <span class="sale-status sale-${s.payment_status || 'pending'}">${statusLabels[s.payment_status] || 'Pendiente'}</span>
                    </div>
                    <div style="text-align:right">
                        <div style="font-size:1.5rem;font-weight:800;color:var(--color-primary)">${total}</div>
                    </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.5rem;font-size:0.88rem;color:var(--text-secondary)">
                    <div><strong>Fecha:</strong> ${new Date(s.sale_date).toLocaleDateString('es-MX', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</div>
                    <div><strong>Cliente:</strong> ${s.client_name || 'N/A'}</div>
                </div>
                ${s.notes ? `<p style="margin-top:0.75rem;padding:0.5rem 0.75rem;background:var(--bg-input);border-radius:8px;font-size:0.85rem"><strong>Notas:</strong> ${s.notes}</p>` : ''}
            </div>`;

            if (items.length) {
                html += '<h4 style="margin-bottom:0.5rem">Artículos</h4>';
                html += '<table class="data-table"><thead><tr><th>Descripción</th><th>Cant.</th><th>Precio</th><th>Subtotal</th></tr></thead><tbody>';
                items.forEach(i => {
                    const sub = parseFloat(i.total || (i.unit_price * i.quantity) || 0).toLocaleString('es-MX', {style:'currency', currency:'MXN'});
                    const price = parseFloat(i.unit_price || 0).toLocaleString('es-MX', {style:'currency', currency:'MXN'});
                    const desc = i.description || i.animal_name || '—';
                    html += `<tr><td>${desc}</td><td>${i.quantity}</td><td>${price}</td><td><strong>${sub}</strong></td></tr>`;
                });
                html += '</tbody></table>';
            }

            // Payment status actions
            if (s.payment_status !== 'paid') {
                html += `<div style="margin-top:1rem;display:flex;gap:0.5rem;justify-content:flex-end">
                    <button class="btn btn-sm btn-primary" onclick="Sales.markPaid(${s.id})">Marcar como Pagada</button>
                </div>`;
            }

            $('#saleDetailContent').html(html);
            Modal.open('saleDetailModal');
        } catch(e) { Toast.danger('Error al cargar detalle'); }
    },

    async markPaid(id) {
        try {
            await API.put(`/sales/${id}`, { payment_status: 'paid' });
            Toast.success('Venta marcada como pagada');
            Modal.close('saleDetailModal');
            this.loadSales();
            this.loadStats();
        } catch(e) { Toast.danger('Error al actualizar'); }
    },

    async deleteSale(id) {
        if (!confirm('¿Eliminar esta venta? Esta acción no se puede deshacer.')) return;
        try {
            await API.delete(`/sales/${id}`);
            Toast.success('Venta eliminada');
            this.loadSales();
            this.loadStats();
        } catch(e) { Toast.danger('Error al eliminar venta'); }
    },
};

$(document).ready(() => Sales.init());
