let absencesData = [];
let employeesData = [];
let rankingData = [];
let absencesCurrentPeriod = 'month';

async function loadAbsencesPage() {
    const content = document.getElementById('main-content');
    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">Faltas</h1>
                <button onclick="openAbsenceModal()" 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-absence">
                    <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>
                    Nova Falta
                </button>
            </div>

            <!-- Period Filter -->
            <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">
                    <button onclick="filterByPeriod('month')" id="filter-month" class="px-4 py-2 rounded-lg font-medium transition-colors bg-zinc-800 text-white" data-testid="filter-month">
                        Mês Atual
                    </button>
                    <button onclick="filterByPeriod('semester')" id="filter-semester" class="px-4 py-2 rounded-lg font-medium transition-colors bg-white text-black border border-gray-300" data-testid="filter-semester">
                        Semestre
                    </button>
                    <button onclick="filterByPeriod('year')" id="filter-year" class="px-4 py-2 rounded-lg font-medium transition-colors bg-white text-black border border-gray-300" data-testid="filter-year">
                        Ano
                    </button>
                </div>
            </div>

            <!-- Ranking Table -->
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow border border-gray-200 dark:border-zinc-700">
                <div class="p-4 border-b border-gray-200 dark:border-zinc-700">
                    <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Ranking de Faltas</h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400">Do funcionário que menos falta para o que mais falta</p>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full" data-testid="table-ranking">
                        <thead class="bg-gray-50 dark:bg-zinc-900">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Posição</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Funcionário</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">CPF</th>
                                <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Justificadas</th>
                                <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Não Justificadas</th>
                                <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total</th>
                            </tr>
                        </thead>
                        <tbody id="ranking-tbody" class="divide-y divide-gray-200 dark:divide-zinc-700">
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Recent Absences -->
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow border border-gray-200 dark:border-zinc-700">
                <div class="p-4 border-b border-gray-200 dark:border-zinc-700">
                    <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Faltas Registradas</h2>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full" data-testid="table-absences">
                        <thead class="bg-gray-50 dark:bg-zinc-900">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Data</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Funcionário</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Tipo</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Descrição</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Atestado</th>
                                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Ações</th>
                            </tr>
                        </thead>
                        <tbody id="absences-tbody" class="divide-y divide-gray-200 dark:divide-zinc-700">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Modal -->
        <div id="absence-modal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center p-4">
            <div class="bg-white dark:bg-zinc-800 rounded-lg shadow-xl w-full max-w-md">
                <div class="p-4 border-b border-gray-200 dark:border-zinc-700 flex justify-between items-center">
                    <h3 id="modal-title" class="text-lg font-semibold text-gray-900 dark:text-white">Nova Falta</h3>
                    <button onclick="closeAbsenceModal()" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
                        <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"></path>
                        </svg>
                    </button>
                </div>
                <form id="absence-form" onsubmit="saveAbsence(event)" class="p-4 space-y-4">
                    <input type="hidden" id="absence-id">
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Funcionário *</label>
                        <select id="absence-employee" required class="w-full 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" data-testid="select-employee">
                            <option value="">Selecione um funcionário</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tipo *</label>
                        <select id="absence-type" required class="w-full 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" data-testid="select-type">
                            <option value="unjustified">Não Justificada</option>
                            <option value="justified">Justificada</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Data *</label>
                        <input type="date" id="absence-date" required class="w-full 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" data-testid="input-date">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Descrição</label>
                        <textarea id="absence-description" rows="3" class="w-full 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" placeholder="Motivo da falta..." data-testid="input-description"></textarea>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Atestado (PDF ou Imagem)</label>
                        <input type="file" id="absence-certificate" accept=".pdf,.jpg,.jpeg,.png,.gif" class="w-full 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 file:mr-4 file:py-1 file:px-3 file:rounded file:border-0 file:bg-gray-100 dark:file:bg-zinc-600 file:text-gray-700 dark:file:text-gray-200" data-testid="input-certificate">
                    </div>

                    <div class="flex gap-3 pt-4">
                        <button type="button" onclick="closeAbsenceModal()" class="flex-1 px-4 py-2 border border-gray-300 dark:border-zinc-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-zinc-700 transition-colors">
                            Cancelar
                        </button>
                        <button type="submit" class="flex-1 px-4 py-2 bg-white hover:bg-gray-200 text-black font-medium rounded-lg transition-colors" data-testid="button-save-absence">
                            Salvar
                        </button>
                    </div>
                </form>
            </div>
        </div>
    `;

    await loadEmployees();
    await loadAbsences();
    await loadRanking();
    updatePeriodButtons();
}

async function loadEmployees() {
    try {
        const response = await fetch('api/employees.php', { credentials: 'include' });
        employeesData = await response.json();
        
        const select = document.getElementById('absence-employee');
        if (select) {
            select.innerHTML = '<option value="">Selecione um funcionário</option>';
            employeesData.filter(e => e.active == 1).forEach(emp => {
                select.innerHTML += `<option value="${emp.id}">${emp.name}</option>`;
            });
        }
    } catch (error) {
        console.error('Erro ao carregar funcionários:', error);
    }
}

async function loadAbsences() {
    try {
        const response = await fetch(`api/absences.php?period=${absencesCurrentPeriod}`, { credentials: 'include' });
        absencesData = await response.json();
        renderAbsences();
    } catch (error) {
        console.error('Erro ao carregar faltas:', error);
    }
}

async function loadRanking() {
    try {
        const response = await fetch(`api/absences.php?action=ranking&period=${absencesCurrentPeriod}`, { credentials: 'include' });
        rankingData = await response.json();
        renderRanking();
    } catch (error) {
        console.error('Erro ao carregar ranking:', error);
    }
}

function renderRanking() {
    const tbody = document.getElementById('ranking-tbody');
    if (!tbody) return;

    if (rankingData.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                    Nenhum funcionário encontrado
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = rankingData.map((emp, index) => {
        const position = index + 1;
        let medalClass = '';
        let medalIcon = '';
        
        if (position === 1) {
            medalClass = 'text-yellow-500';
            medalIcon = '🥇';
        } else if (position === 2) {
            medalClass = 'text-gray-400';
            medalIcon = '🥈';
        } else if (position === 3) {
            medalClass = 'text-amber-600';
            medalIcon = '🥉';
        }

        return `
            <tr class="hover:bg-gray-50 dark:hover:bg-zinc-700/50" data-testid="row-ranking-${emp.id}">
                <td class="px-4 py-3 whitespace-nowrap">
                    <span class="${medalClass} font-bold">${medalIcon} ${position}º</span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap text-gray-900 dark:text-white font-medium">${emp.name}</td>
                <td class="px-4 py-3 whitespace-nowrap text-gray-500 dark:text-gray-400">${emp.cpf || '-'}</td>
                <td class="px-4 py-3 whitespace-nowrap text-center">
                    <span class="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
                        ${emp.justified_count}
                    </span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap text-center">
                    <span class="px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400">
                        ${emp.unjustified_count}
                    </span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap text-center">
                    <span class="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-zinc-700 dark:text-gray-300">
                        ${emp.total_absences}
                    </span>
                </td>
            </tr>
        `;
    }).join('');
}

function renderAbsences() {
    const tbody = document.getElementById('absences-tbody');
    if (!tbody) return;

    if (absencesData.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                    Nenhuma falta registrada no período
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = absencesData.map(absence => {
        const typeLabel = absence.absence_type === 'justified' ? 
            '<span class="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">Justificada</span>' :
            '<span class="px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400">Não Justificada</span>';
        
        const certificateLink = absence.certificate_path ? 
            `<a href="${absence.certificate_path}" target="_blank" class="text-blue-500 hover:text-blue-700 flex items-center gap-1">
                <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="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path>
                </svg>
                Ver
            </a>` : '-';

        return `
            <tr class="hover:bg-gray-50 dark:hover:bg-zinc-700/50" data-testid="row-absence-${absence.id}">
                <td class="px-4 py-3 whitespace-nowrap text-gray-900 dark:text-white">${formatDate(absence.absence_date)}</td>
                <td class="px-4 py-3 whitespace-nowrap text-gray-900 dark:text-white font-medium">${absence.employee_name}</td>
                <td class="px-4 py-3 whitespace-nowrap">${typeLabel}</td>
                <td class="px-4 py-3 text-gray-500 dark:text-gray-400 max-w-xs truncate">${absence.description || '-'}</td>
                <td class="px-4 py-3 whitespace-nowrap">${certificateLink}</td>
                <td class="px-4 py-3 whitespace-nowrap text-right">
                    <button onclick="editAbsence('${absence.id}')" class="text-blue-500 hover:text-blue-700 mr-2" data-testid="button-edit-${absence.id}">
                        <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="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"></path>
                        </svg>
                    </button>
                    <button onclick="deleteAbsence('${absence.id}')" class="text-red-500 hover:text-red-700" data-testid="button-delete-${absence.id}">
                        <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="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"></path>
                        </svg>
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const [year, month, day] = dateStr.split('-');
    return `${day}/${month}/${year}`;
}

function filterByPeriod(period) {
    absencesCurrentPeriod = period;
    updatePeriodButtons();
    loadAbsences();
    loadRanking();
}

function updatePeriodButtons() {
    const periods = ['month', 'semester', 'year'];
    periods.forEach(p => {
        const btn = document.getElementById(`filter-${p}`);
        if (btn) {
            if (p === absencesCurrentPeriod) {
                btn.className = 'px-4 py-2 rounded-lg font-medium transition-colors bg-zinc-800 text-white';
            } else {
                btn.className = 'px-4 py-2 rounded-lg font-medium transition-colors bg-white text-black border border-gray-300';
            }
        }
    });
}

function openAbsenceModal(id = null) {
    const modal = document.getElementById('absence-modal');
    const title = document.getElementById('modal-title');
    const form = document.getElementById('absence-form');
    
    form.reset();
    document.getElementById('absence-id').value = '';
    document.getElementById('absence-date').value = new Date().toISOString().split('T')[0];
    
    if (id) {
        title.textContent = 'Editar Falta';
        const absence = absencesData.find(a => a.id === id);
        if (absence) {
            document.getElementById('absence-id').value = absence.id;
            document.getElementById('absence-employee').value = absence.employee_id;
            document.getElementById('absence-type').value = absence.absence_type;
            document.getElementById('absence-date').value = absence.absence_date;
            document.getElementById('absence-description').value = absence.description || '';
        }
    } else {
        title.textContent = 'Nova Falta';
    }
    
    modal.classList.remove('hidden');
    modal.classList.add('flex');
}

function closeAbsenceModal() {
    const modal = document.getElementById('absence-modal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}

async function saveAbsence(event) {
    event.preventDefault();
    
    const id = document.getElementById('absence-id').value;
    const formData = new FormData();
    
    formData.append('employee_id', document.getElementById('absence-employee').value);
    formData.append('absence_type', document.getElementById('absence-type').value);
    formData.append('absence_date', document.getElementById('absence-date').value);
    formData.append('description', document.getElementById('absence-description').value);
    
    const certificateFile = document.getElementById('absence-certificate').files[0];
    if (certificateFile) {
        formData.append('certificate', certificateFile);
    }
    
    try {
        let response;
        if (id) {
            const data = {
                id: id,
                employee_id: document.getElementById('absence-employee').value,
                absence_type: document.getElementById('absence-type').value,
                absence_date: document.getElementById('absence-date').value,
                description: document.getElementById('absence-description').value
            };
            response = await fetch('api/absences.php', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify(data)
            });
        } else {
            response = await fetch('api/absences.php', {
                method: 'POST',
                credentials: 'include',
                body: formData
            });
        }
        
        const result = await response.json();
        
        if (result.success || result.id) {
            closeAbsenceModal();
            await loadAbsences();
            await loadRanking();
            showNotification('Falta salva com sucesso!', 'success');
        } else {
            showNotification(result.error || 'Erro ao salvar falta', 'error');
        }
    } catch (error) {
        console.error('Erro ao salvar:', error);
        showNotification('Erro ao salvar falta', 'error');
    }
}

async function editAbsence(id) {
    openAbsenceModal(id);
}

async function deleteAbsence(id) {
    if (!confirm('Tem certeza que deseja excluir esta falta?')) return;
    
    try {
        const response = await fetch('api/absences.php', {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify({ id })
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadAbsences();
            await loadRanking();
            showNotification('Falta excluída com sucesso!', 'success');
        } else {
            showNotification(result.error || 'Erro ao excluir falta', 'error');
        }
    } catch (error) {
        console.error('Erro ao excluir:', error);
        showNotification('Erro ao excluir falta', 'error');
    }
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 ${
        type === 'success' ? 'bg-green-500 text-white' : 
        type === 'error' ? 'bg-red-500 text-white' : 
        'bg-blue-500 text-white'
    }`;
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => notification.remove(), 3000);
}
