/**
 * Vaccines — Plataforma Ganadera
 * Gestión de catálogo de vacunas, aplicaciones, próximas dosis y estadísticas
 */
const Vaccines = {
    page: 1,
    searchTerm: '',
    speciesFilter: '',
    dateFrom: '',
    dateTo: '',

    async init() {
        this.setupTabs();
        this.bindEvents();
        await Promise.all([
            this.loadApplications(),
            this.loadUpcoming(),
            this.loadCatalog(),
            this.loadStats()
        ]);
    },

    bindEvents() {
        // Search on applications tab
        $(document).on('input', '#vaccSearchApp', App.debounce(() => {
            this.searchTerm = $('#vaccSearchApp').val();
            this.page = 1;
            this.loadApplications();
        }, 300));

        // Filter by species
        $(document).on('change', '#vaccSpeciesFilter', () => {
            this.speciesFilter = $('#vaccSpeciesFilter').val();
            this.page = 1;
            this.loadApplications();
        });

        // Filter by date range
        $(document).on('change', '#vaccDateFrom, #vaccDateTo', () => {
            this.dateFrom = $('#vaccDateFrom').val();
            this.dateTo = $('#vaccDateTo').val();
            this.page = 1;
            this.loadApplications();
        });
    },

    setupTabs() {
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
                tab.classList.add('active');
                document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
            });
        });
    },

    async loadStats() {
        try {
            const res = await API.get('/vaccines/upcoming?days=30');
            const items = res.data || [];
            const today = new Date();
            const overdue = items.filter(i => new Date(i.next_dose_date) < today).length;
            const thisWeek = items.filter(i => {
                const d = Math.ceil((new Date(i.next_dose_date) - today) / 86400000);
                return d >= 0 && d <= 7;
            }).length;
            const thisMonth = items.filter(i => {
                const d = Math.ceil((new Date(i.next_dose_date) - today) / 86400000);
                return d >= 0 && d <= 30;
            }).length;

            // Inject stats into alerts area if exists
            const alertArea = document.getElementById('vaccineAlerts');
            if (alertArea) {
                let html = '';
                if (overdue > 0) {
                    html += `<div class="vaccine-alert-banner" style="border-color:rgba(220,53,69,0.4);background:rgba(220,53,69,0.08);margin-bottom:0.5rem">
                        <span class="alert-count" style="color:#B91C1C">${overdue}</span>
                        <span style="color:#B91C1C;font-weight:600">vacunas vencidas — requieren atención inmediata</span>
                    </div>`;
                }
                if (thisWeek > 0) {
                    html += `<div class="vaccine-alert-banner">
                        <span class="alert-count">${thisWeek}</span>
                        <span>vacunas con refuerzo en los próximos 7 días</span>
                    </div>`;
                }
                if (!html) {
                    html = '';
                }
                alertArea.innerHTML = html;
            }
        } catch(e) {}
    },

    async loadApplications() {
        let url = `/vaccines/applications?page=${this.page}&per_page=20`;
        if (this.searchTerm) url += `&search=${encodeURIComponent(this.searchTerm)}`;
        if (this.speciesFilter) url += `&species_id=${this.speciesFilter}`;
        if (this.dateFrom) url += `&from_date=${this.dateFrom}`;
        if (this.dateTo) url += `&to_date=${this.dateTo}`;

        try {
            const res = await API.get(url);
            const items = res.data || [];

            document.getElementById('applicationsBody').innerHTML = items.length
                ? items.map(v => {
                    const nextDays = v.next_dose_date ? Math.ceil((new Date(v.next_dose_date) - new Date()) / 86400000) : null;
                    let nextBadge = '—';
                    if (v.next_dose_date) {
                        const cls = nextDays !== null && nextDays < 0 ? 'chip-danger' : nextDays <= 7 ? 'chip-warning' : 'chip-success';
                        const label = nextDays < 0 ? 'Vencida' : nextDays === 0 ? 'HOY' : nextDays === 1 ? 'Mañana' : `En ${nextDays}d`;
                        nextBadge = `<span class="chip ${cls}" title="${App.formatDate(v.next_dose_date)}">${label}</span>`;
                    }
                    return `<tr>
                        <td><a href="/animales/${v.animal_id}" class="link-primary">${v.animal_name || v.tag_id}</a></td>
                        <td><strong>${v.vaccine_name}</strong></td>
                        <td>${App.formatDate(v.application_date)}</td>
                        <td>${v.dose || '—'}</td>
                        <td>${v.batch_number || '—'}</td>
                        <td>${nextBadge}</td>
                        <td>${v.applied_by_name || '—'}</td>
                    </tr>`;
                }).join('')
                : '<tr><td colspan="7" class="text-center"><div class="empty-state"><p>Sin aplicaciones registradas</p></div></td></tr>';

            // Pagination
            if (res.meta && res.meta.total) {
                App.renderPagination('#appsPagination', res.meta, (p) => {
                    this.page = p;
                    this.loadApplications();
                });
            }
        } catch(e) {
            document.getElementById('applicationsBody').innerHTML = '<tr><td colspan="7">Error al cargar</td></tr>';
        }
    },

    async loadUpcoming() {
        try {
            const res = await API.get('/vaccines/upcoming?days=60');
            const items = res.data || [];
            const container = document.getElementById('upcomingList');

            container.innerHTML = items.length 
                ? items.map(v => {
                    const days = Math.ceil((new Date(v.next_dose_date) - new Date()) / 86400000);
                    const cls = days < 0 ? 'urgent' : days <= 3 ? 'urgent' : days <= 14 ? 'soon' : 'normal';
                    const dayLabel = days < 0 ? `Vencida hace ${Math.abs(days)}d` : days === 0 ? 'HOY' : days === 1 ? 'Mañana' : `En ${days} días`;
                    return `<div class="upcoming-card">
                        <div class="upcoming-info">
                            <div class="upcoming-animal">
                                <a href="/animales/${v.animal_id}" class="link-primary"><strong>${v.animal_name || v.tag_id}</strong></a>
                                <span class="text-muted" style="margin-left:0.5rem;font-size:0.82rem">${v.species_name || ''}</span>
                            </div>
                            <div style="font-size:0.85rem;color:var(--text-muted);margin-top:0.25rem">
                                ${Icons.syringe ? Icons.syringe(14) : '💉'} ${v.vaccine_name} — ${App.formatDate(v.next_dose_date)}
                            </div>
                        </div>
                        <div class="upcoming-actions">
                            <span class="days-left ${cls}">${dayLabel}</span>
                            <a href="/vacunas/aplicar" class="btn btn-sm btn-primary" style="margin-left:0.5rem" title="Aplicar ahora">Aplicar</a>
                        </div>
                    </div>`;
                }).join('')
                : '<div class="empty-state"><p>Sin vacunaciones próximas — ¡todo al día!</p></div>';
        } catch(e) {
            document.getElementById('upcomingList').innerHTML = '<div class="empty-state"><p>Error al cargar</p></div>';
        }
    },

    async loadCatalog() {
        try {
            const res = await API.get('/vaccines');
            const items = res.data || [];
            document.getElementById('catalogBody').innerHTML = items.length
                ? items.map(v => `<tr>
                    <td><strong>${v.name}</strong>${v.description ? `<div style="font-size:0.75rem;color:var(--text-muted)">${v.description}</div>` : ''}</td>
                    <td>${v.manufacturer || '—'}</td>
                    <td>${v.dose_ml ? v.dose_ml + ' ml' : '—'}</td>
                    <td>${v.booster_days ? v.booster_days + ' días' : '—'}</td>
                    <td>${v.applicable_species || 'Todas'}</td>
                    <td>
                        <button class="btn btn-sm btn-ghost" onclick="Vaccines.editCatalog(${v.id})" title="Editar">${Icons.edit(14)}</button>
                        <button class="btn btn-sm btn-ghost text-danger" onclick="Vaccines.deleteCatalog(${v.id})" title="Eliminar">${Icons.trash(14)}</button>
                    </td>
                </tr>`).join('')
                : '<tr><td colspan="6">Sin vacunas en catálogo</td></tr>';
        } catch(e) {
            document.getElementById('catalogBody').innerHTML = '<tr><td colspan="6">Error al cargar catálogo</td></tr>';
        }
    },

    async editCatalog(id) {
        try {
            const res = await API.get(`/vaccines/${id}`);
            const v = res.data;
            const html = `<form id="editVaccForm">
                <div class="form-group"><label class="form-label">Nombre *</label><input type="text" class="form-input" id="evName" value="${v.name || ''}" required></div>
                <div class="form-group"><label class="form-label">Descripción</label><textarea class="form-textarea" id="evDesc" rows="2">${v.description || ''}</textarea></div>
                <div class="form-row">
                    <div class="form-group"><label class="form-label">Fabricante</label><input type="text" class="form-input" id="evManuf" value="${v.manufacturer || ''}"></div>
                    <div class="form-group"><label class="form-label">Dosis (ml)</label><input type="number" class="form-input" id="evDose" step="0.01" value="${v.dose_ml || ''}"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label class="form-label">Días para refuerzo</label><input type="number" class="form-input" id="evBooster" value="${v.booster_days || ''}"></div>
                    <div class="form-group"><label class="form-label">Especies aplicables</label><input type="text" class="form-input" id="evSpecies" value="${v.applicable_species || ''}"></div>
                </div>
            </form>`;

            Modal.confirm(html, 'Guardar cambios').then(async () => {
                const data = {
                    name: $('#evName').val(),
                    description: $('#evDesc').val() || null,
                    manufacturer: $('#evManuf').val() || null,
                    dose_ml: $('#evDose').val() || null,
                    booster_days: $('#evBooster').val() || null,
                    applicable_species: $('#evSpecies').val() || null,
                };
                await API.put(`/vaccines/${id}`, data);
                Toast.success('Vacuna actualizada');
                this.loadCatalog();
            }).catch(() => {});
        } catch(e) { Toast.danger('Error al cargar vacuna'); }
    },

    async deleteCatalog(id) {
        if (!confirm('¿Eliminar esta vacuna del catálogo?')) return;
        try {
            await API.delete(`/vaccines/${id}`);
            Toast.success('Vacuna eliminada');
            this.loadCatalog();
        } catch(e) { Toast.danger('Error al eliminar'); }
    }
};

document.addEventListener('DOMContentLoaded', () => Vaccines.init());
