/**
 * Movements — Plataforma Ganadera
 * Registrar y consultar traslados, cambios de corral/lote, ingresos y salidas
 */
const Movements = {
    page: 1,
    stats: {},

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

    bindEvents() {
        $('#movTypeFilter, #movFromDate, #movToDate').on('change', () => { this.page = 1; this.loadMovements(); });
        $('#movForm').on('submit', (e) => { e.preventDefault(); this.save(); });

        // Search for animals in movement modal
        $(document).on('input', '#movAnimalSearch', App.debounce(() => {
            const term = $('#movAnimalSearch').val().toLowerCase();
            $('#movAnimals option').each(function() {
                $(this).toggle($(this).text().toLowerCase().includes(term));
            });
        }, 200));
    },

    async loadStats() {
        try {
            const today = new Date().toISOString().split('T')[0];
            const monthStart = today.substring(0, 8) + '01';
            const res = await API.get(`/movements?from_date=${monthStart}&to_date=${today}&per_page=500`);
            const items = res.data || [];
            const transfers = items.filter(m => m.movement_type === 'ranch_transfer').length;
            const locationChanges = items.filter(m => m.movement_type === 'location_change').length;
            const entries = items.filter(m => m.movement_type === 'entry').length;
            const exits = items.filter(m => m.movement_type === 'exit').length;

            this.stats = { total: items.length, transfers, locationChanges, entries, exits };

            // Render mini stats above filters if container exists
            const statsContainer = document.getElementById('movStats');
            if (statsContainer) {
                statsContainer.innerHTML = `
                    <div class="stat-card"><div class="stat-value">${items.length}</div><div class="stat-label">Total Mes</div></div>
                    <div class="stat-card"><div class="stat-value">${transfers}</div><div class="stat-label">Traslados</div></div>
                    <div class="stat-card"><div class="stat-value">${locationChanges}</div><div class="stat-label">Cambio Corral</div></div>
                    <div class="stat-card"><div class="stat-value">${entries}</div><div class="stat-label">Ingresos</div></div>
                    <div class="stat-card"><div class="stat-value">${exits}</div><div class="stat-label">Salidas</div></div>
                `;
            }
        } catch(e) {}
    },

    async loadLocations() {
        try {
            const res = await API.get('/locations');
            const locations = res.data || [];
            const opts = locations.map(l => `<option value="${l.name || l.code}">${l.name}${l.type ? ' (' + l.type + ')' : ''}</option>`).join('');
            if (document.getElementById('movOriginSelect')) {
                $('#movOriginSelect').html('<option value="">— Sin especificar —</option>' + opts);
                $('#movDestSelect').html('<option value="">— Sin especificar —</option>' + opts);
            }
        } catch(e) {}
    },

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

    async loadMovements() {
        let url = `/movements?page=${this.page}&per_page=25`;
        const type = $('#movTypeFilter').val();
        const from = $('#movFromDate').val();
        const to = $('#movToDate').val();
        if (type) url += `&movement_type=${type}`;
        if (from) url += `&from_date=${from}`;
        if (to) url += `&to_date=${to}`;

        try {
            const res = await API.get(url);
            this.render(res.data || []);
            if (res.meta && res.meta.total) {
                App.renderPagination('#movPagination', res.meta, (p) => {
                    this.page = p;
                    this.loadMovements();
                });
            }
        } catch(e) {
            $('#movBody').html('<tr><td colspan="6" class="text-center">Error al cargar</td></tr>');
        }
    },

    render(movements) {
        if (!movements.length) {
            $('#movBody').html('<tr><td colspan="6" class="text-center text-muted"><div class="empty-state"><p>Sin movimientos registrados</p></div></td></tr>');
            return;
        }

        const typeLabels = {
            'ranch_transfer': 'Traslado',
            'location_change': 'Cambio Corral',
            'lot_change': 'Cambio Lote',
            'entry': 'Ingreso',
            'exit': 'Salida'
        };

        const html = movements.map(m => {
            const date = new Date(m.movement_date || m.created_at);
            const dateStr = date.toLocaleDateString('es-MX', { day: '2-digit', month: 'short', year: 'numeric' });
            const typeLabel = typeLabels[m.movement_type] || m.movement_type.replace('_', ' ');
            const animalInfo = m.animal_name
                ? `<a href="/animales/${m.animal_id}" class="link-primary">${m.animal_name}</a>`
                : (m.animal_count ? `${m.animal_count} animal(es)` : '—');

            return `<tr>
                <td>${dateStr}</td>
                <td>${animalInfo}</td>
                <td><span class="mov-badge mov-${m.movement_type}">${typeLabel}</span></td>
                <td>${m.origin || m.from_location || '—'}</td>
                <td>${m.destination || m.to_location || '—'}</td>
                <td>${m.performed_by_name || '—'}</td>
            </tr>`;
        }).join('');
        $('#movBody').html(html);
    },

    showModal() {
        $('#movForm')[0].reset();
        document.getElementById('movDate').value = new Date().toISOString().split('T')[0];
        Modal.open('movModal');
    },

    async save() {
        const selected = Array.from(document.getElementById('movAnimals').selectedOptions).map(o => parseInt(o.value));
        if (!selected.length) { Toast.warning('Selecciona al menos un animal'); return; }

        const type = $('#movFormType').val();
        const data = {
            movement_type: type,
            animal_ids: selected,
            origin: $('#movOrigin').val() || null,
            destination: $('#movDestination').val() || null,
            movement_date: $('#movDate').val() || null,
            notes: $('#movNotes').val() || null,
        };

        try {
            await API.post('/movements', data);
            Modal.close('movModal');
            Toast.success(`Movimiento registrado — ${selected.length} animal(es)`);
            await Promise.all([this.loadMovements(), this.loadStats()]);
        } catch(e) { Toast.danger('Error al registrar movimiento'); }
    }
};

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