const Inventory = {
    items: [],
    categories: [],
    page: 1,

    async init() {
        this.bindEvents();
        await Promise.all([this.loadCategories(), this.loadItems(), this.loadAlerts(), this.loadMovements()]);
    },

    bindEvents() {
        $('#invSearch').on('input', App.debounce(() => { this.page = 1; this.loadItems(); }, 300));
        $('#invCategory, #invStockFilter').on('change', () => { this.page = 1; this.loadItems(); });
        $('#itemForm').on('submit', (e) => { e.preventDefault(); this.saveItem(); });
        $('#movementForm').on('submit', (e) => { e.preventDefault(); this.saveMovement(); });
    },

    async loadCategories() {
        try {
            const res = await API.get('/inventory/categories');
            this.categories = res.data || [];
            const options = '<option value="">Todas</option>' + this.categories.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
            $('#invCategory').html(options);
            $('#itemCategory').html('<option value="">General</option>' + this.categories.map(c => `<option value="${c.id}">${c.name}</option>`).join(''));
        } catch(e) {}
    },

    async loadItems() {
        let url = `/inventory?page=${this.page}&per_page=20`;
        const search = $('#invSearch').val();
        const category = $('#invCategory').val();
        const stockFilter = $('#invStockFilter').val();
        if (search) url += `&search=${encodeURIComponent(search)}`;
        if (category) url += `&category_id=${category}`;

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

            if (stockFilter === 'low') items = items.filter(i => i.current_stock > 0 && i.current_stock <= (i.min_stock || 0));
            else if (stockFilter === 'out') items = items.filter(i => i.current_stock <= 0);
            else if (stockFilter === 'ok') items = items.filter(i => i.current_stock > (i.min_stock || 0));

            this.items = items;
            this.renderItems(items);
            this.updateStats(res);
        } catch(e) {
            $('#inventoryBody').html('<tr><td colspan="7" class="text-center">Error al cargar inventario</td></tr>');
        }
    },

    formatStock(val) {
        const n = parseFloat(val || 0);
        return n % 1 === 0 ? n.toFixed(0) : n.toFixed(2).replace(/0+$/, '');
    },

    renderItems(items) {
        if (!items.length) {
            $('#inventoryBody').html('<tr><td colspan="7" class="text-center text-muted">Sin artículos registrados</td></tr>');
            return;
        }
        const html = items.map(item => {
            const stock = parseFloat(item.current_stock || 0);
            const minStock = parseFloat(item.min_stock || 0);
            const stockClass = stock <= 0 ? 'stock-out' : stock <= minStock ? 'stock-low' : 'stock-ok';
            const stockLabel = stock <= 0 ? 'Sin Stock' : stock <= minStock ? 'Bajo' : 'OK';
            const expiry = item.expiry_date ? new Date(item.expiry_date).toLocaleDateString('es-MX') : '—';
            const unit = item.unit || 'uds';
            return `<tr>
                <td><strong>${item.name}</strong>${item.description ? `<br><small class="text-muted">${item.description}</small>` : ''}</td>
                <td>${item.category_name || 'General'}</td>
                <td><span class="stock-badge ${stockClass}">${this.formatStock(stock)} ${stockLabel}</span></td>
                <td>${this.formatStock(minStock)}</td>
                <td>${unit}</td>
                <td>${expiry}</td>
                <td><button class="btn btn-sm btn-ghost" onclick="Inventory.editItem(${item.id})">✏️</button></td>
            </tr>`;
        }).join('');
        $('#inventoryBody').html(html);
    },

    updateStats(res) {
        const items = res.data || [];
        const total = (res.meta && res.meta.total) || items.length;
        $('#statTotal').text(total);
        $('#statLowStock').text(items.filter(i => i.current_stock > 0 && i.current_stock <= (i.min_stock || 0)).length);
        const cats = new Set(items.map(i => i.category_name || 'General'));
        $('#statCategories').text(cats.size);
    },

    async loadAlerts() {
        try {
            const res = await API.get('/inventory/alerts');
            const alerts = res.data || {};
            const lowStock = alerts.low_stock || [];
            const expiring = alerts.expiring || [];
            $('#statExpiring').text(expiring.length);
            if (lowStock.length || expiring.length) {
                let html = '<h4>⚠️ Alertas de Inventario</h4><ul>';
                lowStock.forEach(a => html += `<li><strong>${a.name}</strong> — Stock bajo (${a.current_stock}/${a.min_stock})</li>`);
                expiring.forEach(a => html += `<li><strong>${a.name}</strong> — Vence: ${new Date(a.expiry_date).toLocaleDateString('es-MX')}</li>`);
                html += '</ul>';
                $('#inventoryAlerts').html(html).show();
            }
        } catch(e) {}
    },

    async loadMovements() {
        const typeLabels = {
            entry: 'Entrada', exit: 'Salida', adjustment: 'Ajuste',
            return: 'Devolución', expired: 'Expirado', usage: 'Uso'
        };
        try {
            const res = await API.get('/inventory/movements?per_page=15');
            const movs = res.data || [];
            if (!movs.length) { $('#movementsBody').html('<tr><td colspan="6" class="text-center text-muted">Sin movimientos registrados</td></tr>'); return; }
            const html = movs.map(m => {
                const label = typeLabels[m.type] || m.type;
                const isIn = ['entry', 'return', 'adjustment'].includes(m.type);
                const sign = isIn ? '+' : '-';
                const signClass = isIn ? 'text-success' : 'text-danger';
                return `<tr>
                <td>${new Date(m.movement_date || m.created_at).toLocaleDateString('es-MX')}</td>
                <td>${m.item_name || '—'}</td>
                <td><span class="mov-type mov-${m.type}">${label}</span></td>
                <td class="${signClass}" style="font-weight:600">${sign}${Inventory.formatStock(m.quantity)}</td>
                <td>${m.new_stock != null ? Inventory.formatStock(m.new_stock) : '—'}</td>
                <td>${m.reason || m.notes || '—'}</td>
            </tr>`;
            }).join('');
            $('#movementsBody').html(html);
        } catch(e) {}
    },

    showCreateModal() {
        $('#itemModalTitle').text('Nuevo Artículo');
        $('#itemForm')[0].reset();
        $('#itemId').val('');
        Modal.open('itemModal');
    },

    async editItem(id) {
        try {
            const res = await API.get(`/inventory/${id}`);
            const item = res.data;
            $('#itemModalTitle').text('Editar Artículo');
            $('#itemId').val(item.id);
            $('#itemName').val(item.name);
            $('#itemCategory').val(item.category_id || '');
            $('#itemUnit').val(item.unit || '');
            $('#itemStock').val(item.current_stock || 0);
            $('#itemMinStock').val(item.min_stock || 0);
            $('#itemCost').val(item.cost_per_unit || '');
            $('#itemSupplier').val(item.supplier || '');
            $('#itemBatch').val(item.batch_number || '');
            $('#itemExpiry').val(item.expiry_date || '');
            $('#itemDesc').val(item.description || '');
            Modal.open('itemModal');
        } catch(e) { Toast.danger('Error al cargar artículo'); }
    },

    async saveItem() {
        const id = $('#itemId').val();
        const data = {
            name: $('#itemName').val(),
            category_id: $('#itemCategory').val() || null,
            unit: $('#itemUnit').val() || null,
            current_stock: parseFloat($('#itemStock').val()) || 0,
            min_stock: parseFloat($('#itemMinStock').val()) || 0,
            cost_per_unit: parseFloat($('#itemCost').val()) || null,
            supplier: $('#itemSupplier').val() || null,
            batch_number: $('#itemBatch').val() || null,
            expiry_date: $('#itemExpiry').val() || null,
            description: $('#itemDesc').val() || null,
        };
        try {
            if (id) await API.put(`/inventory/${id}`, data);
            else await API.post('/inventory', data);
            Modal.close('itemModal');
            Toast.success(id ? 'Artículo actualizado' : 'Artículo creado');
            this.loadItems();
            this.loadAlerts();
        } catch(e) { Toast.danger('Error al guardar'); }
    },

    showMovementModal() {
        $('#movementForm')[0].reset();
        const opts = this.items.map(i => `<option value="${i.id}">${i.name} (${this.formatStock(i.current_stock)} ${i.unit || 'uds'})</option>`).join('');
        $('#movItem').html('<option value="">Seleccionar...</option>' + opts);
        // Default date = today
        document.getElementById('movDate').value = new Date().toISOString().split('T')[0];
        // Show/hide supplier based on type
        this.toggleSupplierField();
        $('#movType').off('change.supplier').on('change.supplier', () => this.toggleSupplierField());
        Modal.open('movementModal');
    },

    toggleSupplierField() {
        const type = $('#movType').val();
        const el = document.getElementById('movSupplierGroup');
        if (el) el.style.display = (type === 'entry' || type === 'return') ? '' : 'none';
    },

    async saveMovement() {
        const data = {
            item_id: $('#movItem').val(),
            type: $('#movType').val(),
            quantity: parseFloat($('#movQuantity').val()),
            movement_date: $('#movDate').val() || new Date().toISOString().split('T')[0],
            supplier: $('#movSupplier')?.val() || null,
            reason: $('#movNotes').val() || null,
        };
        if (!data.item_id || !data.quantity) { Toast.warning('Artículo y cantidad son obligatorios'); return; }
        try {
            const res = await API.post('/inventory/movements', data);
            Modal.close('movementModal');
            const newStock = res.data?.new_stock;
            Toast.success(`Movimiento registrado${newStock !== undefined ? ' — Stock: ' + newStock : ''}`);
            this.loadItems();
            this.loadMovements();
            this.loadAlerts();
        } catch(e) { Toast.danger('Error al registrar movimiento'); }
    },
};

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