const Disposals = {
    page: 1,
    evidenceFile: null,

    typeLabels: {
        death: 'Muerte',
        slaughter: 'Sacrificio',
        sale_discard: 'Descarte venta',
        lost: 'Extravío',
        theft: 'Robo',
        discard: 'Descarte',
        other: 'Otro',
    },
    typeColors: {
        death: 'danger',
        slaughter: 'warning',
        sale_discard: 'info',
        lost: 'purple',
        theft: 'danger',
        discard: 'warning',
        other: 'muted',
    },

    async init() {
        this.bindEvents();
        document.getElementById('dispDate').value = new Date().toISOString().split('T')[0];
        await Promise.all([this.loadDisposals(), this.loadStats(), this.loadAnimals()]);
    },

    bindEvents() {
        $('#dispType, #dispFrom, #dispTo').on('change', () => { this.page = 1; this.loadDisposals(); });
        $('#disposalForm').on('submit', (e) => { e.preventDefault(); this.save(); });
        $('#searchDisposal').on('input', App.debounce(() => { this.page = 1; this.loadDisposals(); }, 400));

        // Photo evidence
        const photoArea = document.getElementById('dispPhotoArea');
        const photoInput = document.getElementById('dispPhoto');
        if (photoArea && photoInput) {
            photoArea.addEventListener('click', () => photoInput.click());
            photoInput.addEventListener('change', (e) => {
                if (e.target.files[0]) {
                    this.evidenceFile = e.target.files[0];
                    const reader = new FileReader();
                    reader.onload = (ev) => {
                        document.getElementById('dispPhotoPreview').innerHTML = `<img src="${ev.target.result}" style="max-height:80px; border-radius:8px">`;
                    };
                    reader.readAsDataURL(this.evidenceFile);
                }
            });
        }
    },

    async loadAnimals() {
        try {
            const res = await API.get('/animals?per_page=500&status=active');
            const animals = res.data || [];
            $('#dispAnimal').html('<option value="">Seleccionar animal...</option>' +
                animals.map(a => `<option value="${a.id}">${a.name || a.tag_id} — ${a.species_name || ''}</option>`).join(''));
        } catch(e) {}
    },

    async loadDisposals() {
        let url = `/disposals?page=${this.page}&per_page=20`;
        const type = $('#dispType').val();
        const from = $('#dispFrom').val();
        const to = $('#dispTo').val();
        const search = $('#searchDisposal').val();
        if (type) url += `&disposal_type=${type}`;
        if (from) url += `&from_date=${from}`;
        if (to) url += `&to_date=${to}`;
        if (search) url += `&search=${encodeURIComponent(search)}`;

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

    renderDisposals(items) {
        if (!items.length) {
            $('#disposalsBody').html('<tr><td colspan="7" class="text-center"><div class="empty-state"><p>Sin bajas registradas</p><p class="text-muted">Registra bajas por muerte, descarte, robo u otros motivos</p></div></td></tr>');
            return;
        }
        const html = items.map(d => {
            const typeLabel = this.typeLabels[d.disposal_type] || d.disposal_type;
            const typeColor = this.typeColors[d.disposal_type] || 'muted';
            return `<tr>
                <td>${App.formatDate(d.disposal_date)}</td>
                <td>
                    <a href="/animales/${d.animal_id}" class="link-primary"><strong>${d.animal_name || d.tag_id || '#' + d.animal_id}</strong></a>
                    ${d.breed_name ? `<div style="font-size:0.75rem;color:var(--text-muted)">${d.breed_name}</div>` : ''}
                </td>
                <td>${d.species_name || '—'}</td>
                <td><span class="chip chip-${typeColor}">${typeLabel}</span></td>
                <td>${d.cause || d.reason || d.description || '—'}</td>
                <td style="max-width:200px">${d.notes ? `<span style="font-size:0.82rem;color:var(--text-secondary)">${d.notes}</span>` : '—'}</td>
                <td>
                    <div style="display:flex; gap:4px;">
                        <button class="btn btn-sm btn-ghost" onclick="Disposals.viewDetail(${d.id})" title="Ver detalle">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                        </button>
                        <button class="btn btn-sm btn-ghost text-danger" onclick="Disposals.deleteDisposal(${d.id})" title="Eliminar">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                        </button>
                    </div>
                </td>
            </tr>`;
        }).join('');
        $('#disposalsBody').html(html);
    },

    async loadStats() {
        try {
            const res = await API.get('/reports/mortality');
            const data = res.data || {};
            const $deaths = $('#statDeaths');
            const $discards = $('#statDiscards');
            const $other = $('#statOther');
            const $rate = $('#statRate');

            // Animate counters
            if (typeof App.animateCounter === 'function') {
                App.animateCounter($deaths[0], data.total_deaths || 0, 800);
                App.animateCounter($discards[0], data.total_discards || 0, 800);
                App.animateCounter($other[0], data.total_other || 0, 800);
            } else {
                $deaths.text(data.total_deaths || 0);
                $discards.text(data.total_discards || 0);
                $other.text(data.total_other || 0);
            }
            $rate.text((data.mortality_rate || 0).toFixed(1) + '%');
        } catch(e) {}
    },

    async viewDetail(id) {
        try {
            const res = await API.get(`/disposals/${id}`);
            const d = res.data || {};
            const typeLabel = this.typeLabels[d.disposal_type] || d.disposal_type;

            Modal.show({
                title: 'Detalle de Baja',
                body: `
                    <div class="detail-grid" style="display:grid; grid-template-columns:1fr 1fr; gap:12px;">
                        <div><label class="text-muted" style="font-size:0.78rem;display:block">Animal</label><strong>${d.animal_name || d.tag_id || '#' + d.animal_id}</strong></div>
                        <div><label class="text-muted" style="font-size:0.78rem;display:block">Especie</label>${d.species_name || '—'}</div>
                        <div><label class="text-muted" style="font-size:0.78rem;display:block">Tipo de baja</label><span class="chip chip-${this.typeColors[d.disposal_type] || 'muted'}">${typeLabel}</span></div>
                        <div><label class="text-muted" style="font-size:0.78rem;display:block">Fecha</label>${App.formatDate(d.disposal_date)}</div>
                        <div style="grid-column:span 2"><label class="text-muted" style="font-size:0.78rem;display:block">Causa / Motivo</label>${d.cause || d.reason || '—'}</div>
                        <div style="grid-column:span 2"><label class="text-muted" style="font-size:0.78rem;display:block">Notas</label>${d.notes || '—'}</div>
                        ${d.registered_by_name ? `<div style="grid-column:span 2"><label class="text-muted" style="font-size:0.78rem;display:block">Registrado por</label>${d.registered_by_name}</div>` : ''}
                    </div>
                `,
                footer: '<button class="btn btn-outline modal-close">Cerrar</button>',
            });
        } catch(e) {
            Toast.danger('Error al cargar detalle');
        }
    },

    async deleteDisposal(id) {
        if (!confirm('¿Eliminar este registro de baja? Esta acción no se puede deshacer.')) return;
        try {
            await API.delete(`/disposals/${id}`);
            Toast.success('Registro eliminado');
            this.loadDisposals();
            this.loadStats();
        } catch(e) {
            Toast.danger('Error al eliminar');
        }
    },

    showModal() { Modal.open('disposalModal'); },

    async save() {
        const animalId = $('#dispAnimal').val();
        const data = {
            animal_id: animalId,
            disposal_type: $('#dispDisposalType').val(),
            disposal_date: $('#dispDate').val(),
            reason: $('#dispReason').val() || null,
            notes: $('#dispNotes').val() || null,
        };
        if (!data.animal_id) { Toast.warning('Selecciona un animal'); return; }
        try {
            await API.post('/disposals', data);
            // Upload evidence photo if selected
            if (this.evidenceFile && animalId) {
                try { await API.upload(`/animals/${animalId}/photos`, this.evidenceFile, 'photo'); } catch(pe) {}
            }
            Modal.close('disposalModal');
            Toast.success('Baja registrada exitosamente');
            this.evidenceFile = null;
            const preview = document.getElementById('dispPhotoPreview');
            if (preview) preview.innerHTML = '📷 Tomar foto de evidencia';
            this.loadDisposals();
            this.loadStats();
            this.loadAnimals();
        } catch(e) { Toast.danger('Error al registrar baja'); }
    },

};

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