/**
 * Lot Detail — Plataforma Ganadera
 * Vista detalle de un lote: animales vinculados, agregar/remover, editar lote
 */
const PURPOSE_LABELS = {
    production: 'Producción', fattening: 'Engorda', breeding: 'Reproducción',
    raising: 'Cría', quarantine: 'Cuarentena', sale: 'Venta'
};

const LotDetail = {
    lotId: null,
    data: null,
    selectedAnimals: new Set(),
    allAnimals: [],

    async init() {
        this.lotId = document.getElementById('lotDetail')?.dataset.lotId;
        if (!this.lotId) return;

        await this.loadLot();
        this.bindEvents();
    },

    bindEvents() {
        // Search within lot
        document.getElementById('searchAnimalsInLot')?.addEventListener('input',
            App.debounce(() => this.renderAnimalsTable(), 300));

        // Search available animals in modal
        document.getElementById('searchAvailable')?.addEventListener('input',
            App.debounce(() => this.searchAvailableAnimals(), 400));
        document.getElementById('filterAvailableSpecies')?.addEventListener('change',
            () => this.searchAvailableAnimals());
    },

    // ─── CARGAR LOTE ─────────────────────────────────────

    async loadLot() {
        const res = await API.get(`/lots/${this.lotId}`);
        if (!res.success) {
            document.getElementById('lotTitle').textContent = 'Lote no encontrado';
            return;
        }
        this.data = res.data;
        this.render();
    },

    // ─── RENDER ──────────────────────────────────────────

    render() {
        const lot = this.data;

        // Title
        document.getElementById('lotTitle').textContent = lot.name;

        // Chips
        const chips = [];
        if (lot.purpose) chips.push(`<span class="chip chip-${lot.purpose}">${PURPOSE_LABELS[lot.purpose] || lot.purpose}</span>`);
        if (lot.species_name) chips.push(`<span class="chip">${lot.species_name}</span>`);
        if (lot.location_name) chips.push(`<span class="chip">${lot.location_name}</span>`);
        if (lot.code) chips.push(`<span class="chip">${lot.code}</span>`);
        document.getElementById('lotChips').innerHTML = chips.join('');

        // KPIs
        const count = parseInt(lot.animal_count) || 0;
        const cap = parseInt(lot.capacity) || 0;
        const pct = cap > 0 ? Math.round((count / cap) * 100) : '—';

        document.getElementById('kpiCount').textContent = count;
        document.getElementById('kpiCapacity').textContent = cap || 'Sin límite';
        document.getElementById('kpiOccupancy').textContent = pct === '—' ? '—' : pct + '%';
        document.getElementById('kpiSpecies').textContent = lot.species_name || 'General';

        // Animals table
        this.renderAnimalsTable();
    },

    renderAnimalsTable() {
        const wrap = document.getElementById('lotAnimalsWrap');
        const animals = this.data?.animals || [];
        const search = (document.getElementById('searchAnimalsInLot')?.value || '').toLowerCase();

        const filtered = search
            ? animals.filter(a =>
                (a.name || '').toLowerCase().includes(search) ||
                (a.tag_id || '').toLowerCase().includes(search) ||
                (a.internal_id || '').toLowerCase().includes(search))
            : animals;

        if (!filtered.length) {
            wrap.innerHTML = `<div style="text-align:center;padding:2rem;color:var(--text-muted)">
                <p style="font-weight:600;margin-bottom:0.5rem">${animals.length ? 'Sin resultados' : 'No hay animales en este lote'}</p>
                ${!animals.length ? '<button class="btn btn-primary btn-sm" onclick="LotDetail.openAddAnimals()">+ Agregar Animales</button>' : ''}
            </div>`;
            return;
        }

        let html = `<table class="lot-animals-table">
            <thead>
                <tr>
                    <th>Animal</th>
                    <th>Arete</th>
                    <th>Especie</th>
                    <th>Raza</th>
                    <th>Sexo</th>
                    <th>Estado</th>
                    <th></th>
                </tr>
            </thead><tbody>`;

        filtered.forEach(a => {
            const photo = a.primary_photo
                ? `<img src="/${a.primary_photo}" class="lot-animal-thumb" alt="">`
                : `<div class="lot-animal-thumb"></div>`;
            const sexLabel = a.sex === 'male' ? 'M' : a.sex === 'female' ? 'H' : '—';
            const statusChip = this.getStatusChip(a.status);
            const healthChip = a.health_status && a.health_status !== 'healthy'
                ? ` <span class="chip chip-sm chip-warning">${a.health_status}</span>` : '';

            html += `<tr>
                <td>
                    <div class="animal-name-cell" onclick="location.href='/animales/${a.id}'">
                        ${photo}
                        <span>${a.name || a.tag_id || '#' + a.id}</span>
                    </div>
                </td>
                <td>${a.tag_id || '—'}</td>
                <td>${a.species_name || '—'}</td>
                <td>${a.breed_name || '—'}</td>
                <td>${sexLabel}</td>
                <td>${statusChip}${healthChip}</td>
                <td><button class="btn-remove-animal" onclick="LotDetail.removeAnimal(${a.id}, '${(a.name || a.tag_id || '').replace(/'/g, "\\'")}')" title="Remover del lote">&times;</button></td>
            </tr>`;
        });

        html += '</tbody></table>';
        wrap.innerHTML = html;
    },

    getStatusChip(status) {
        const map = {
            active: '<span class="chip chip-sm chip-success">Activo</span>',
            sold: '<span class="chip chip-sm chip-info">Vendido</span>',
            disposed: '<span class="chip chip-sm chip-warning">Baja</span>',
            dead: '<span class="chip chip-sm chip-danger">Muerto</span>'
        };
        return map[status] || `<span class="chip chip-sm">${status || '—'}</span>`;
    },

    // ─── REMOVER ANIMAL ──────────────────────────────────

    async removeAnimal(animalId, name) {
        if (!confirm(`¿Remover "${name}" de este lote?`)) return;

        const res = await API.delete(`/lots/${this.lotId}/animals`, { animal_ids: [animalId] });
        if (res.success) {
            Toast.success('Animal removido del lote');
            this.loadLot();
        } else {
            Toast.error(res.error || 'Error al remover');
        }
    },

    // ─── AGREGAR ANIMALES ────────────────────────────────

    async openAddAnimals() {
        this.selectedAnimals.clear();
        this.updateSelectedCount();
        document.getElementById('searchAvailable').value = '';
        document.getElementById('availableAnimalsList').innerHTML =
            '<p style="padding:1rem;color:var(--text-muted)">Escribe para buscar animales disponibles...</p>';

        // Load species filter
        try {
            const res = await API.get('/species');
            const sel = document.getElementById('filterAvailableSpecies');
            sel.innerHTML = '<option value="">Todas las especies</option>' +
                (res.data || []).map(s => `<option value="${s.id}">${s.name}</option>`).join('');
        } catch(e) {}

        Modal.open('addAnimalsModal');
        document.getElementById('searchAvailable')?.focus();
    },

    async searchAvailableAnimals() {
        const search = document.getElementById('searchAvailable')?.value || '';
        const speciesId = document.getElementById('filterAvailableSpecies')?.value || '';
        const list = document.getElementById('availableAnimalsList');

        if (search.length < 1 && !speciesId) {
            list.innerHTML = '<p style="padding:1rem;color:var(--text-muted)">Escribe para buscar animales disponibles...</p>';
            return;
        }

        let url = '/animals?per_page=50&status=active';
        if (search) url += `&search=${encodeURIComponent(search)}`;
        if (speciesId) url += `&species_id=${speciesId}`;

        try {
            const res = await API.get(url);
            this.allAnimals = res.data || [];
            this.renderAvailableAnimals();
        } catch(e) {
            list.innerHTML = '<p style="padding:1rem;color:var(--text-muted)">Error buscando animales</p>';
        }
    },

    renderAvailableAnimals() {
        const list = document.getElementById('availableAnimalsList');
        const currentLotAnimals = (this.data?.animals || []).map(a => a.id);

        if (!this.allAnimals.length) {
            list.innerHTML = '<p style="padding:1rem;color:var(--text-muted)">Sin resultados</p>';
            return;
        }

        list.innerHTML = this.allAnimals.map(a => {
            const inThisLot = currentLotAnimals.includes(a.id);
            const checked = this.selectedAnimals.has(a.id) ? 'checked' : '';
            const lotInfo = a.lot_id ? (a.lot_id == this.lotId ? '(ya en este lote)' : `(en otro lote)`) : '';

            return `<label class="avail-animal-row ${checked ? 'selected' : ''} ${inThisLot ? 'in-lot' : ''}">
                <input type="checkbox" value="${a.id}" ${checked} ${inThisLot ? 'disabled' : ''}
                    onchange="LotDetail.toggleAnimal(${a.id}, this.checked)">
                <span class="avail-animal-name">${a.name || a.tag_id || '#' + a.id}</span>
                <span class="avail-animal-meta">${a.species_name || ''} ${a.breed_name ? '· ' + a.breed_name : ''} · ${a.sex === 'male' ? 'M' : a.sex === 'female' ? 'H' : '—'}</span>
                ${lotInfo ? `<span class="avail-animal-lot">${lotInfo}</span>` : ''}
            </label>`;
        }).join('');
    },

    toggleAnimal(id, checked) {
        if (checked) {
            this.selectedAnimals.add(id);
        } else {
            this.selectedAnimals.delete(id);
        }
        this.updateSelectedCount();
    },

    updateSelectedCount() {
        const count = this.selectedAnimals.size;
        const info = document.getElementById('addAnimalsInfo');
        const btn = document.getElementById('btnConfirmAdd');
        if (info) {
            info.style.display = count > 0 ? 'block' : 'none';
            document.getElementById('selectedCount').textContent = count;
        }
        if (btn) btn.disabled = count === 0;
    },

    async confirmAddAnimals() {
        if (!this.selectedAnimals.size) return;

        const res = await API.post(`/lots/${this.lotId}/animals`, {
            animal_ids: Array.from(this.selectedAnimals)
        });

        if (res.success) {
            Toast.success(res.data?.message || 'Animales agregados');
            Modal.close('addAnimalsModal');
            this.loadLot();
        } else {
            Toast.error(res.error || 'Error al agregar');
        }
    },

    // ─── EDITAR LOTE ─────────────────────────────────────

    openEdit() {
        const lot = this.data;
        if (!lot) return;

        document.getElementById('editLotName').value = lot.name || '';
        document.getElementById('editLotCode').value = lot.code || '';
        document.getElementById('editLotPurpose').value = lot.purpose || '';
        document.getElementById('editLotCapacity').value = lot.capacity || '';
        document.getElementById('editLotDescription').value = lot.description || '';

        Modal.open('editLotModal');
    },

    async saveEdit() {
        const data = {
            name: document.getElementById('editLotName').value.trim(),
            code: document.getElementById('editLotCode').value.trim() || null,
            purpose: document.getElementById('editLotPurpose').value || null,
            capacity: document.getElementById('editLotCapacity').value || null,
            description: document.getElementById('editLotDescription').value.trim() || null,
        };

        if (!data.name) { Toast.warning('El nombre es obligatorio'); return; }

        const res = await API.put(`/lots/${this.lotId}`, data);
        if (res.success) {
            Toast.success('Lote actualizado');
            Modal.close('editLotModal');
            this.loadLot();
        } else {
            Toast.error(res.error || 'Error al actualizar');
        }
    },
};

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