let consumptionData = [];
let consumptionGrouped = [];
let consumptionEmployees = [];
let consumptionStockItems = [];
let consumptionBranches = [];
let consumptionPeriod = 'month';
let consumptionFilters = {};

async function loadEmployeeConsumptionsPage() {
    const content = document.getElementById('main-content');
    content.innerHTML = '<div class="flex justify-center items-center h-64"><div class="spinner"></div></div>';

    try {
        const [empRes, branchRes, stockRes] = await Promise.all([
            fetch('api/employees.php', { credentials: 'include' }),
            fetch('api/branches.php', { credentials: 'include' }),
            fetch('api/stock-items.php', { credentials: 'include' })
        ]);
        const empData = await empRes.json();
        const branchData = await branchRes.json();
        const stockData = await stockRes.json();
        consumptionEmployees = empData.employees || empData || [];
        consumptionBranches = branchData.branches || branchData || [];
        consumptionStockItems = stockData.items || [];
    } catch (e) {
        consumptionEmployees = [];
        consumptionBranches = [];
        consumptionStockItems = [];
    }

    renderConsumptionPage();
}

async function renderConsumptionPage() {
    const content = document.getElementById('main-content');

    try {
        const params = new URLSearchParams();
        if (consumptionFilters.employee_id) params.append('employee_id', consumptionFilters.employee_id);
        if (consumptionFilters.branch_id) params.append('branch_id', consumptionFilters.branch_id);
        if (consumptionFilters.date_start && consumptionFilters.date_end) {
            params.append('date_start', consumptionFilters.date_start);
            params.append('date_end', consumptionFilters.date_end);
        } else {
            params.append('period', consumptionPeriod);
        }

        const res = await fetch(`api/employee-consumptions.php?${params.toString()}`, { credentials: 'include' });
        const data = await res.json();
        consumptionData = data.consumptions || [];
        consumptionGrouped = data.grouped || [];
    } catch (e) {
        consumptionData = [];
        consumptionGrouped = [];
    }

    const empOptions = consumptionEmployees.map(e => `<option value="${e.id}" ${consumptionFilters.employee_id === e.id ? 'selected' : ''}>${e.name}</option>`).join('');
    const branchOptions = consumptionBranches.map(b => `<option value="${b.id}" ${consumptionFilters.branch_id === b.id ? 'selected' : ''}>${b.name}</option>`).join('');

    const periodButtons = [
        { key: 'day', label: 'Dia' },
        { key: 'week', label: 'Semana' },
        { key: 'biweekly', label: 'Quinzena' },
        { key: 'month', label: 'Mês' },
        { key: 'bimonthly', label: 'Bimestre' },
        { key: 'semester', label: 'Semestre' },
        { key: 'year', label: 'Anual' }
    ];

    const useCustomPeriod = consumptionFilters.date_start && consumptionFilters.date_end;

    content.innerHTML = `
        <div class="space-y-6">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Consumo Funcionário</h1>
                <button onclick="openConsumptionModal()" class="bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center gap-2" data-testid="button-new-consumption">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                    Novo Consumo
                </button>
            </div>

            <!-- Filtro de Período -->
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                <div class="flex flex-wrap gap-2 mb-3">
                    ${periodButtons.map(p => `
                        <button onclick="setConsumptionPeriod('${p.key}')" id="cp-filter-${p.key}" class="px-4 py-2 rounded-lg font-medium transition-colors ${!useCustomPeriod && consumptionPeriod === p.key ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-${p.key}">
                            ${p.label}
                        </button>
                    `).join('')}
                    <button onclick="toggleCustomPeriod()" id="cp-filter-custom" class="px-4 py-2 rounded-lg font-medium transition-colors ${useCustomPeriod ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-custom">
                        Período
                    </button>
                </div>
                <div class="flex flex-wrap gap-3 items-end">
                    <div>
                        <label class="block text-xs font-medium text-gray-500 mb-1">Funcionário</label>
                        <select id="cp-filter-employee" onchange="applyConsumptionFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="select-cp-employee">
                            <option value="">Todos</option>
                            ${empOptions}
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-500 mb-1">Filial</label>
                        <select id="cp-filter-branch" onchange="applyConsumptionFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="select-cp-branch">
                            <option value="">Todas</option>
                            ${branchOptions}
                        </select>
                    </div>
                    <div id="cp-custom-dates" class="${useCustomPeriod ? 'flex' : 'hidden'} gap-2">
                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">De</label>
                            <input type="date" id="cp-date-start" value="${consumptionFilters.date_start || ''}" onchange="applyConsumptionFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-cp-date-start">
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">Até</label>
                            <input type="date" id="cp-date-end" value="${consumptionFilters.date_end || ''}" onchange="applyConsumptionFilter()" class="px-3 py-2 border border-gray-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-700 text-gray-900 dark:text-white text-sm" data-testid="input-cp-date-end">
                        </div>
                    </div>
                    <button onclick="clearConsumptionFilters()" class="px-3 py-2 text-sm text-gray-500 hover:text-gray-700" data-testid="button-clear-cp-filters">
                        Limpar
                    </button>
                </div>
            </div>

            <!-- Cartões Resumo -->
            <div class="flex flex-wrap gap-4">
                <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                    <p class="text-sm text-gray-500">Funcionários</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">${consumptionGrouped.length}</p>
                </div>
                <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                    <p class="text-sm text-gray-500">Total Itens</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">${consumptionData.length}</p>
                </div>
                <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 border border-gray-200 dark:border-zinc-700">
                    <p class="text-sm text-gray-500">Valor Total</p>
                    <p class="text-2xl font-bold text-red-600">${formatMoney(consumptionGrouped.reduce((s, g) => s + g.total, 0))}</p>
                </div>
            </div>

            <!-- Agrupado por Funcionário -->
            ${consumptionGrouped.length === 0 ? `
                <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-8 border border-gray-200 dark:border-zinc-700 text-center text-gray-500">
                    Nenhum consumo registrado no período selecionado
                </div>
            ` : consumptionGrouped.map(group => `
                <div class="bg-white dark:bg-zinc-800 rounded-lg shadow border border-gray-200 dark:border-zinc-700 overflow-hidden" data-testid="group-employee-${group.employee_id}">
                    <div class="px-4 py-3 bg-gray-50 dark:bg-zinc-900 flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <div class="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white text-sm font-medium">
                                ${group.employee_name.charAt(0).toUpperCase()}
                            </div>
                            <span class="font-semibold text-gray-900 dark:text-white">${group.employee_name}</span>
                            <span class="text-sm text-gray-500">(${group.items.length} itens)</span>
                        </div>
                        <span class="font-bold text-red-600 text-lg">${formatMoney(group.total)}</span>
                    </div>
                    <table class="min-w-full divide-y divide-gray-200 dark:divide-zinc-700">
                        <thead>
                            <tr>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Data</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Item</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Qtd</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">V. Unit.</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Total</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Filial</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Ações</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 dark:divide-zinc-700">
                            ${group.items.map(item => `
                                <tr class="hover:bg-gray-50 dark:hover:bg-zinc-700/50">
                                    <td class="px-4 py-2 text-gray-900 dark:text-white text-sm">${formatDate(item.consumption_date)}</td>
                                    <td class="px-4 py-2 font-medium text-gray-900 dark:text-white text-sm">${item.item_name}</td>
                                    <td class="px-4 py-2 text-gray-600 dark:text-gray-300 text-sm">${parseFloat(item.quantity).toLocaleString('pt-BR')}</td>
                                    <td class="px-4 py-2 text-gray-600 dark:text-gray-300 text-sm">${formatMoney(item.item_value)}</td>
                                    <td class="px-4 py-2 font-medium text-red-600 text-sm">${formatMoney(parseFloat(item.item_value) * parseFloat(item.quantity))}</td>
                                    <td class="px-4 py-2 text-gray-600 dark:text-gray-300 text-sm">${item.branch_name || '-'}</td>
                                    <td class="px-4 py-2">
                                        <div class="flex gap-2">
                                            <button onclick="openConsumptionModal('${item.id}')" class="text-blue-500 hover:text-blue-700" title="Editar" data-testid="button-edit-cp-${item.id}">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                            </button>
                                            <button onclick="deleteConsumption('${item.id}')" class="text-red-500 hover:text-red-700" title="Excluir" data-testid="button-delete-cp-${item.id}">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `).join('')}
        </div>
    `;
}

function setConsumptionPeriod(period) {
    consumptionPeriod = period;
    consumptionFilters.date_start = '';
    consumptionFilters.date_end = '';
    renderConsumptionPage();
}

function toggleCustomPeriod() {
    const dates = document.getElementById('cp-custom-dates');
    if (dates.classList.contains('hidden')) {
        dates.classList.remove('hidden');
        dates.classList.add('flex');
        consumptionFilters.date_start = document.getElementById('cp-date-start')?.value || '';
        consumptionFilters.date_end = document.getElementById('cp-date-end')?.value || '';
    } else {
        dates.classList.add('hidden');
        dates.classList.remove('flex');
        consumptionFilters.date_start = '';
        consumptionFilters.date_end = '';
        renderConsumptionPage();
    }
}

function applyConsumptionFilter() {
    consumptionFilters.employee_id = document.getElementById('cp-filter-employee')?.value || '';
    consumptionFilters.branch_id = document.getElementById('cp-filter-branch')?.value || '';
    consumptionFilters.date_start = document.getElementById('cp-date-start')?.value || '';
    consumptionFilters.date_end = document.getElementById('cp-date-end')?.value || '';
    renderConsumptionPage();
}

function clearConsumptionFilters() {
    consumptionPeriod = 'month';
    consumptionFilters = {};
    renderConsumptionPage();
}

function openConsumptionModal(id = null) {
    const item = id ? consumptionData.find(c => c.id === id) : null;

    const empOptions = consumptionEmployees.map(e => `<option value="${e.id}" ${item && item.employee_id === e.id ? 'selected' : ''}>${e.name}</option>`).join('');
    const branchOptions = consumptionBranches.map(b => `<option value="${b.id}" ${item && item.branch_id === b.id ? 'selected' : ''}>${b.name}</option>`).join('');

    const stockOptions = consumptionStockItems.map(s =>
        `<option value="${s.id}" data-price="${s.sale_price}" data-name="${s.name}" ${item && item.stock_item_id === s.id ? 'selected' : ''}>${s.name} (${formatMoney(s.sale_price)})</option>`
    ).join('');

    const isOther = item && !item.stock_item_id;

    const modal = document.createElement('div');
    modal.id = 'consumption-modal';
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/50';
    modal.innerHTML = `
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">${item ? 'Editar Consumo' : 'Novo Consumo'}</h3>
                    <button onclick="closeConsumptionModal()" class="text-gray-500 hover:text-gray-700"><svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg></button>
                </div>
                <form onsubmit="saveConsumption(event, '${id || ''}')" class="space-y-4">
                    <div>
                        <label class="form-label">Funcionário *</label>
                        <select id="cp-employee" required class="form-input" data-testid="select-cp-employee-modal">
                            <option value="">Selecione</option>
                            ${empOptions}
                        </select>
                    </div>
                    <div>
                        <label class="form-label">Item *</label>
                        <select id="cp-stock-item" onchange="onStockItemChange()" class="form-input" data-testid="select-cp-item">
                            <option value="">Selecione</option>
                            ${stockOptions}
                            <option value="outros" ${isOther ? 'selected' : ''}>OUTROS</option>
                        </select>
                    </div>
                    <div id="cp-other-fields" class="${isOther ? '' : 'hidden'}">
                        <div class="mb-3">
                            <label class="form-label">Nome do Item</label>
                            <input type="text" id="cp-item-name" value="${isOther ? item.item_name : ''}" class="form-input" data-testid="input-cp-item-name">
                        </div>
                        <div>
                            <label class="form-label">Valor do Item</label>
                            <input type="number" step="0.01" id="cp-item-value-manual" value="${isOther ? item.item_value : ''}" class="form-input" data-testid="input-cp-item-value">
                        </div>
                    </div>
                    <div id="cp-auto-value" class="${isOther ? 'hidden' : ''}">
                        <label class="form-label">Valor do Item</label>
                        <input type="number" step="0.01" id="cp-item-value-auto" value="${!isOther && item ? item.item_value : ''}" class="form-input bg-gray-100 dark:bg-zinc-600" readonly data-testid="input-cp-auto-value">
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="form-label">Quantidade</label>
                            <input type="number" step="0.001" id="cp-quantity" value="${item?.quantity || '1'}" min="0.001" required class="form-input" data-testid="input-cp-quantity">
                        </div>
                        <div>
                            <label class="form-label">Data *</label>
                            <input type="date" id="cp-date" value="${item?.consumption_date || new Date().toISOString().split('T')[0]}" required class="form-input" data-testid="input-cp-date">
                        </div>
                    </div>
                    <div>
                        <label class="form-label">Filial</label>
                        <select id="cp-branch" class="form-input" data-testid="select-cp-branch-modal">
                            <option value="">Selecione</option>
                            ${branchOptions}
                        </select>
                    </div>
                    <div class="flex gap-3 pt-2">
                        <button type="submit" class="flex-1 bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg" data-testid="button-save-consumption">Salvar</button>
                        <button type="button" onclick="closeConsumptionModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 font-medium py-2 px-4 rounded-lg">Cancelar</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

function onStockItemChange() {
    const select = document.getElementById('cp-stock-item');
    const otherFields = document.getElementById('cp-other-fields');
    const autoValue = document.getElementById('cp-auto-value');

    if (select.value === 'outros') {
        otherFields.classList.remove('hidden');
        autoValue.classList.add('hidden');
        document.getElementById('cp-item-value-auto').value = '';
    } else if (select.value) {
        otherFields.classList.add('hidden');
        autoValue.classList.remove('hidden');
        const option = select.selectedOptions[0];
        const price = option.dataset.price || '0';
        document.getElementById('cp-item-value-auto').value = price;
    } else {
        otherFields.classList.add('hidden');
        autoValue.classList.remove('hidden');
        document.getElementById('cp-item-value-auto').value = '';
    }
}

function closeConsumptionModal() {
    document.getElementById('consumption-modal')?.remove();
}

async function saveConsumption(e, id) {
    e.preventDefault();

    const stockSelect = document.getElementById('cp-stock-item');
    const isOther = stockSelect.value === 'outros';
    const stockItemId = isOther ? null : stockSelect.value;

    let itemName, itemValue;
    if (isOther) {
        itemName = document.getElementById('cp-item-name').value;
        itemValue = parseFloat(document.getElementById('cp-item-value-manual').value) || 0;
    } else {
        const option = stockSelect.selectedOptions[0];
        itemName = option.dataset.name;
        itemValue = parseFloat(document.getElementById('cp-item-value-auto').value) || 0;
    }

    if (!itemName) {
        alert('Nome do item é obrigatório');
        return;
    }

    const data = {
        employee_id: document.getElementById('cp-employee').value,
        stock_item_id: stockItemId,
        item_name: itemName,
        item_value: itemValue,
        quantity: parseFloat(document.getElementById('cp-quantity').value) || 1,
        consumption_date: document.getElementById('cp-date').value,
        branch_id: document.getElementById('cp-branch').value || null
    };

    if (!data.employee_id) {
        alert('Selecione um funcionário');
        return;
    }

    try {
        const url = id ? `api/employee-consumptions.php?id=${id}` : 'api/employee-consumptions.php';
        const method = id ? 'PUT' : 'POST';
        if (id) data.id = id;

        const res = await fetch(url, {
            method,
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify(data)
        });
        const result = await res.json();
        if (result.success) {
            closeConsumptionModal();
            renderConsumptionPage();
        } else {
            alert(result.error || 'Erro ao salvar');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}

async function deleteConsumption(id) {
    if (!confirm('Excluir este registro de consumo?')) return;

    try {
        const res = await fetch(`api/employee-consumptions.php?id=${id}`, { method: 'DELETE', credentials: 'include' });
        const result = await res.json();
        if (result.success) {
            renderConsumptionPage();
        } else {
            alert(result.error || 'Erro ao excluir');
        }
    } catch (err) {
        alert('Erro de conexão');
    }
}
