/**
 * Lots (Lotes) — Plataforma Ganadera
 * Gestión de lotes: CRUD, filtros, búsqueda, vinculación con animales
 */
const PURPOSE_LABELS = {
    production: 'Producción', fattening: 'Engorda', breeding: 'Reproducción',
    raising: 'Cría', quarantine: 'Cuarentena', sale: 'Venta'
};

const Lots = {
    data: [],

    async init() {
        await Promise.all([this.loadSpecies(), this.loadLocations()]);
        await this.loadLots();

        document.getElementById('searchLots')?.addEventListener('input', App.debounce(() => this.loadLots(), 400));
        document.getElementById('filterSpecies')?.addEventListener('change', () => this.loadLots());
        document.getElementById('filterPurpose')?.addEventListener('change', () => this.loadLots());
    },

    // ─── CARGAR CATÁLOGOS ────────────────────────────────

    async loadSpecies() {
        try {
            const res = await API.get('/species');
            const options = (res.data || []).map(s => `<option value="${s.id}">${s.name}</option>`).join('');
            document.querySelectorAll('#filterSpecies, #lotSpecies').forEach(el => {
                const first = el.options[0].outerHTML;
                el.innerHTML = first + options;
            });
        } catch(e) { console.error('Error loading species:', e); }
    },

    async loadLocations() {
        try {
            const res = await API.get('/locations');
            if (!res.data) return;
            const options = res.data.map(l => `<option value="${l.id}">${l.name} (${l.type})</option>`).join('');
            const el = document.getElementById('lotLocation');
            if (el) {
                const first = el.options[0].outerHTML;
                el.innerHTML = first + options;
            }
        } catch(e) { /* locations may not be available */ }
    },

    // ─── CARGAR LOTES ────────────────────────────────────

    async loadLots() {
        const grid = document.getElementById('lotsGrid');
        const search = document.getElementById('searchLots')?.value || '';
        const speciesId = document.getElementById('filterSpecies')?.value || '';
        const purpose = document.getElementById('filterPurpose')?.value || '';

        try {
            let url = '/lots?per_page=200';
            if (search) url += `&search=${encodeURIComponent(search)}`;
            if (speciesId) url += `&species_id=${speciesId}`;
            if (purpose) url += `&purpose=${purpose}`;

            const res = await API.get(url);
            this.data = res.data || [];
            this.renderGrid();
            this.updateStats();
        } catch(e) {
            grid.innerHTML = '<div class="empty-state" style="grid-column:1/-1"><p>Error al cargar lotes</p></div>';
        }
    },

    // ─── RENDERIZAR GRID ─────────────────────────────────

    renderGrid() {
        const grid = document.getElementById('lotsGrid');
        if (!this.data.length) {
            grid.innerHTML = `<div class="empty-state" style="grid-column:1/-1;text-align:center;padding:3rem">
                <p style="font-size:1.1rem;font-weight:600;margin-bottom:0.5rem">Sin lotes registrados</p>
                <p style="color:var(--text-muted);margin-bottom:1rem">Crea tu primer lote para organizar animales</p>
                <button class="btn btn-primary" onclick="Lots.openCreate()">+ Crear Lote</button>
            </div>`;
            return;
        }

        grid.innerHTML = this.data.map(lot => {
            const count = parseInt(lot.animal_count) || 0;
            const cap = parseInt(lot.capacity) || 0;
            const pct = cap > 0 ? Math.min((count / cap) * 100, 100) : 0;
            const pctClass = pct > 90 ? 'high' : pct > 65 ? 'mid' : 'low';
            const purposeLabel = PURPOSE_LABELS[lot.purpose] || '';

            return `<div class="lot-card" onclick="location.href='/lotes/${lot.id}'">
                <div class="lot-card-actions">
                    <button onclick="event.stopPropagation();Lots.openEdit(${lot.id})" title="Editar">${Icons.edit(14)}</button>
                    <button class="btn-del" onclick="event.stopPropagation();Lots.deleteLot(${lot.id},'${lot.name.replace(/'/g,'\\\'')}')" title="Eliminar">${Icons.trash(14)}</button>
                </div>
                <div class="lot-card-header">
                    <div>
                        <div class="lot-card-name">${lot.name}</div>
                        ${lot.code ? `<div class="lot-card-code">${lot.code}</div>` : ''}
                    </div>
                    ${lot.purpose ? `<span class="lot-card-badge ${lot.purpose}">${purposeLabel}</span>` : ''}
                </div>
                ${lot.description ? `<div class="lot-card-desc">${lot.description}</div>` : ''}
                <div class="lot-card-meta">
                    <span><strong>${count}</strong> animal${count !== 1 ? 'es' : ''}</span>
                    ${cap ? `<span>Cap. <strong>${cap}</strong></span>` : ''}
                    ${lot.species_name ? `<span>${lot.species_name}</span>` : ''}
                    ${lot.location_name ? `<span>${lot.location_name}</span>` : ''}
                </div>
                ${cap ? `<div class="lot-progress"><div class="lot-progress-bar ${pctClass}" style="width:${pct}%"></div></div>` : ''}
            </div>`;
        }).join('');
    },

    // ─── STATS ───────────────────────────────────────────

    updateStats() {
        const total = this.data.length;
        const active = this.data.filter(l => l.is_active).length;
        const animals = this.data.reduce((s, l) => s + (parseInt(l.animal_count) || 0), 0);

        document.getElementById('totalLots').textContent = total;
        document.getElementById('activeLots').textContent = active;
        document.getElementById('totalInLots').textContent = animals;
    },

    // ─── CREAR / EDITAR ──────────────────────────────────

    openCreate() {
        document.getElementById('lotModalTitle').textContent = 'Nuevo Lote';
        document.getElementById('lotId').value = '';
        document.getElementById('lotForm').reset();
        Modal.open('lotModal');
    },

    async openEdit(id) {
        const res = await API.get(`/lots/${id}`);
        if (!res.success) { Toast.error('Error al cargar lote'); return; }
        const lot = res.data;

        document.getElementById('lotModalTitle').textContent = 'Editar Lote';
        document.getElementById('lotId').value = lot.id;
        document.getElementById('lotName').value = lot.name || '';
        document.getElementById('lotCode').value = lot.code || '';
        document.getElementById('lotSpecies').value = lot.species_id || '';
        document.getElementById('lotPurpose').value = lot.purpose || '';
        document.getElementById('lotLocation').value = lot.location_id || '';
        document.getElementById('lotCapacity').value = lot.capacity || '';
        document.getElementById('lotDescription').value = lot.description || '';

        Modal.open('lotModal');
    },

    async save() {
        const id = document.getElementById('lotId').value;
        const data = {
            name: document.getElementById('lotName').value.trim(),
            code: document.getElementById('lotCode').value.trim() || null,
            species_id: document.getElementById('lotSpecies').value || null,
            purpose: document.getElementById('lotPurpose').value || null,
            location_id: document.getElementById('lotLocation').value || null,
            capacity: document.getElementById('lotCapacity').value || null,
            description: document.getElementById('lotDescription').value.trim() || null,
        };

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

        try {
            const res = id
                ? await API.put(`/lots/${id}`, data)
                : await API.post('/lots', data);

            if (res.success) {
                Toast.success(id ? 'Lote actualizado' : 'Lote creado');
                Modal.close('lotModal');
                this.loadLots();
            } else {
                Toast.error(res.error || 'Error al guardar');
            }
        } catch(e) {
            Toast.error('Error al guardar lote');
        }
    },

    // ─── ELIMINAR ────────────────────────────────────────

    async deleteLot(id, name) {
        if (!confirm(`¿Eliminar el lote "${name}"?\nLos animales serán desvinculados del lote.`)) return;

        try {
            const res = await API.delete(`/lots/${id}`);
            Toast.success('Lote eliminado');
            this.loadLots();
        } catch(e) {
            Toast.error('Error al eliminar lote');
        }
    },
};

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