const Reports = {
    chartInstance: null,

    async load(type) {
        const endpoints = {
            'animal-inventory': { url: '/reports/animals', title: 'Inventario Animal' },
            'health': { url: '/reports/health', title: 'Reporte Sanitario' },
            'reproduction': { url: '/reports/reproduction', title: 'Reporte de Reproducción' },
            'mortality': { url: '/reports/mortality', title: 'Mortalidad' },
            'sales': { url: '/reports/sales', title: 'Reporte de Ventas' },
            'inventory': { url: '/reports/inventory', title: 'Inventario de Insumos' },
        };

        const config = endpoints[type];
        if (!config) return;

        $('#reportTitle').text(config.title);
        $('#reportBody').html('<div class="text-center" style="padding:2rem"><div class="spinner"></div> Cargando...</div>');
        $('#reportContent').show();

        try {
            const res = await API.get(config.url);
            this.render(type, res.data || {});
        } catch(e) {
            $('#reportBody').html('<div class="text-center text-muted">Error al cargar reporte</div>');
        }
    },

    render(type, data) {
        const renderers = {
            'animal-inventory': this.renderAnimalInventory,
            'health': this.renderHealth,
            'reproduction': this.renderReproduction,
            'mortality': this.renderMortality,
            'sales': this.renderSales,
            'inventory': this.renderInventory,
        };
        const fn = renderers[type];
        if (fn) fn.call(this, data);
    },

    renderAnimalInventory(data) {
        let html = '<div class="report-summary">';
        html += `<div class="report-kpi"><div class="value">${data.total || 0}</div><div class="label">Total Animales</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.active || 0}</div><div class="label">Activos</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.males || 0}</div><div class="label">Machos</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.females || 0}</div><div class="label">Hembras</div></div>`;
        html += '</div>';

        const bySpecies = data.by_species || [];
        if (bySpecies.length) {
            html += '<h4 style="margin-bottom:0.75rem">Por Especie</h4><table class="report-table"><thead><tr><th>Especie</th><th>Cantidad</th></tr></thead><tbody>';
            bySpecies.forEach(s => html += `<tr><td>${s.species || s.name || s.species_name || 'Sin especie'}</td><td><strong>${s.count || s.total}</strong></td></tr>`);
            html += '</tbody></table>';
            this.renderChart('Animales por Especie', bySpecies.map(s => s.species || s.name || s.species_name || 'Sin especie'), bySpecies.map(s => s.count || s.total), html);
            return;
        }
        $('#reportBody').html(html);
    },

    renderHealth(data) {
        let html = '<div class="report-summary">';
        html += `<div class="report-kpi"><div class="value">${data.total_events || 0}</div><div class="label">Eventos Sanitarios</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.vaccinations || 0}</div><div class="label">Vacunaciones</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.treatments || 0}</div><div class="label">Tratamientos</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.quarantined || 0}</div><div class="label">En Cuarentena</div></div>`;
        html += '</div>';
        $('#reportBody').html(html);
    },

    renderReproduction(data) {
        let html = '<div class="report-summary">';
        html += `<div class="report-kpi"><div class="value">${data.total_pregnancies || 0}</div><div class="label">Gestaciones</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.active_pregnancies || 0}</div><div class="label">Gestaciones Activas</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.total_births || 0}</div><div class="label">Nacimientos</div></div>`;
        html += `<div class="report-kpi"><div class="value">${(data.fertility_rate || 0).toFixed(1)}%</div><div class="label">Tasa Fertilidad</div></div>`;
        html += '</div>';
        $('#reportBody').html(html);
    },

    renderMortality(data) {
        let html = '<div class="report-summary">';
        html += `<div class="report-kpi"><div class="value">${data.total_deaths || 0}</div><div class="label">Total Muertes</div></div>`;
        html += `<div class="report-kpi"><div class="value">${(data.mortality_rate || 0).toFixed(1)}%</div><div class="label">Tasa Mortalidad</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.total_discards || 0}</div><div class="label">Descartes</div></div>`;
        html += '</div>';

        const byCause = data.by_cause || data.by_type || [];
        if (byCause.length) {
            html += '<h4 style="margin:1rem 0 0.75rem">Por Causa</h4><table class="report-table"><thead><tr><th>Causa</th><th>Cantidad</th></tr></thead><tbody>';
            byCause.forEach(c => html += `<tr><td>${c.cause || c.type || c.disposal_type}</td><td>${c.count || c.total}</td></tr>`);
            html += '</tbody></table>';
        }
        $('#reportBody').html(html);
    },

    renderSales(data) {
        let html = '<div class="report-summary">';
        const rev = parseFloat(data.total_revenue || 0).toLocaleString('es-MX', {style:'currency', currency:'MXN'});
        html += `<div class="report-kpi"><div class="value">${data.total_sales || 0}</div><div class="label">Total Ventas</div></div>`;
        html += `<div class="report-kpi"><div class="value">${rev}</div><div class="label">Ingresos</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.animals_sold || 0}</div><div class="label">Animales Vendidos</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.total_clients || 0}</div><div class="label">Clientes</div></div>`;
        html += '</div>';
        $('#reportBody').html(html);
    },

    renderInventory(data) {
        let html = '<div class="report-summary">';
        html += `<div class="report-kpi"><div class="value">${data.total_items || 0}</div><div class="label">Total Artículos</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.low_stock || 0}</div><div class="label">Stock Bajo</div></div>`;
        html += `<div class="report-kpi"><div class="value">${data.expiring || 0}</div><div class="label">Por Vencer</div></div>`;
        html += '</div>';

        const items = data.items || [];
        if (items.length) {
            html += '<h4 style="margin:1rem 0 0.75rem">Artículos</h4><table class="report-table"><thead><tr><th>Nombre</th><th>Stock</th><th>Mínimo</th><th>Estado</th></tr></thead><tbody>';
            items.forEach(i => {
                const status = i.current_stock <= 0 ? '<span style="color:var(--danger)">Sin Stock</span>' : i.current_stock <= (i.min_stock || 0) ? '<span style="color:#f0ad4e">Bajo</span>' : '<span style="color:var(--primary)">OK</span>';
                html += `<tr><td>${i.name}</td><td>${i.current_stock}</td><td>${i.min_stock || 0}</td><td>${status}</td></tr>`;
            });
            html += '</tbody></table>';
        }
        $('#reportBody').html(html);
    },

    renderChart(title, labels, values, existingHtml, chartType = 'doughnut') {
        const html = existingHtml + '<div class="report-chart" style="max-height:320px;margin-top:1rem"><canvas id="reportChart"></canvas></div>';
        $('#reportBody').html(html);
        if (this.chartInstance) this.chartInstance.destroy();
        const ctx = document.getElementById('reportChart').getContext('2d');

        const colors = ['#047857', '#059669', '#0D9488', '#2563EB', '#7C3AED', '#B45309', '#D97706', '#DC2626', '#4F46E5', '#0891B2'];

        this.chartInstance = new Chart(ctx, {
            type: chartType,
            data: {
                labels: labels,
                datasets: [{
                    data: values,
                    backgroundColor: chartType === 'doughnut' ? colors : colors.map(c => c + '20'),
                    borderColor: chartType !== 'doughnut' ? colors : '#fff',
                    borderWidth: chartType === 'doughnut' ? 3 : 2,
                    hoverOffset: chartType === 'doughnut' ? 8 : 0,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                ...(chartType === 'doughnut' ? { cutout: '60%' } : {}),
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { color: '#475569', padding: 12, usePointStyle: true, font: { size: 11 } }
                    }
                },
                animation: { duration: 800, easing: 'easeOutQuart' },
            }
        });
    },

    // ─── EXPORT ─────────────────────────────────────────────

    exportCSV() {
        const table = document.querySelector('#reportBody .report-table');
        if (!table) { Toast.warning('No hay tabla para exportar'); return; }

        let csv = '';
        const rows = table.querySelectorAll('tr');
        rows.forEach(row => {
            const cells = row.querySelectorAll('th, td');
            const values = Array.from(cells).map(c => '"' + c.textContent.replace(/"/g, '""').trim() + '"');
            csv += values.join(',') + '\n';
        });

        const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `reporte_${$('#reportTitle').text().replace(/\s+/g, '_').toLowerCase()}_${new Date().toISOString().split('T')[0]}.csv`;
        a.click();
        URL.revokeObjectURL(url);
        Toast.success('CSV descargado');
    },

    printReport() {
        const content = document.getElementById('reportBody');
        if (!content) return;
        const title = $('#reportTitle').text();
        const printWin = window.open('', '_blank');
        printWin.document.write(`<!DOCTYPE html><html><head><title>${title}</title><style>
            body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; padding: 24px; color: #1e293b; }
            h1 { font-size: 1.4rem; border-bottom: 2px solid #047857; padding-bottom: 8px; margin-bottom: 16px; }
            .report-summary { display: flex; gap: 16px; flex-wrap: wrap; margin-bottom: 16px; }
            .report-kpi { text-align: center; padding: 12px 16px; border: 1px solid #e2e8f0; border-radius: 8px; min-width: 100px; }
            .report-kpi .value { font-size: 1.6rem; font-weight: 700; color: #047857; }
            .report-kpi .label { font-size: 0.78rem; color: #64748b; margin-top: 4px; }
            table { width: 100%; border-collapse: collapse; margin-top: 12px; }
            th, td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #e2e8f0; font-size: 0.85rem; }
            th { background: #f8fafc; font-weight: 600; }
            .report-chart { display: none; }
            .chip { padding: 2px 8px; border-radius: 10px; font-size: 0.75rem; background: #f1f5f9; }
            @media print { body { padding: 0; } }
        </style></head><body>
            <h1>${title}</h1>
            <p style="color:#64748b;font-size:0.85rem;margin-bottom:16px">Generado: ${new Date().toLocaleString('es-MX')}</p>
            ${content.innerHTML}
        </body></html>`);
        printWin.document.close();
        printWin.focus();
        setTimeout(() => printWin.print(), 400);
    },

    hideReport() {
        $('#reportContent').hide();
        if (this.chartInstance) { this.chartInstance.destroy(); this.chartInstance = null; }
    }
};
