// Administrators Page
async function renderAdministrators() {
    const content = document.getElementById('main-content');
    
    try {
        const administrators = await apiRequest('administrators.php');
        
        const colors = [
            { value: '#3B82F6', name: 'Azul' },
            { value: '#22C55E', name: 'Verde' },
            { value: '#EF4444', name: 'Vermelho' },
            { value: '#F59E0B', name: 'Amarelo' },
            { value: '#8B5CF6', name: 'Roxo' },
            { value: '#EC4899', name: 'Rosa' },
            { value: '#14B8A6', name: 'Turquesa' },
            { value: '#F97316', name: 'Laranja' }
        ];
        
        content.innerHTML = `
            <div class="space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <h3 class="text-xl font-semibold text-gray-800 dark:text-white">Administradores</h3>
                    <button onclick="openAdminModal()" class="btn-primary" data-testid="button-new-admin">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                        Novo Administrador
                    </button>
                </div>
                
                <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    ${administrators.filter(a => a.active).map(admin => `
                        <div class="card p-4" data-testid="card-admin-${admin.id}">
                            <div class="flex items-start justify-between">
                                <div class="flex items-center gap-3">
                                    <div class="w-12 h-12 rounded-full flex items-center justify-center text-white text-lg font-medium" style="background-color: ${admin.color || '#3B82F6'}">
                                        ${admin.name.charAt(0).toUpperCase()}
                                    </div>
                                    <div>
                                        <h4 class="font-semibold text-gray-800 dark:text-white">${admin.name}</h4>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">${admin.email}</p>
                                    </div>
                                </div>
                                <div class="flex gap-1">
                                    <button onclick="openAdminModal('${admin.id}')" class="p-1.5 rounded hover:bg-gray-100 dark:hover:bg-zinc-700" title="Editar">
                                        <svg class="w-4 h-4 text-gray-500" 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>
                                    ${admin.id !== currentUser?.id ? `
                                        <button onclick="deleteAdmin('${admin.id}')" class="p-1.5 rounded hover:bg-gray-100 dark:hover:bg-zinc-700" title="Excluir">
                                            <svg class="w-4 h-4 text-red-500" 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>
                            </div>
                            <div class="mt-4 pt-4 border-t border-gray-100 dark:border-zinc-700">
                                <div class="flex items-center gap-2">
                                    <span class="text-sm text-gray-500">Cor:</span>
                                    <div class="w-6 h-6 rounded-full border-2 border-white shadow" style="background-color: ${admin.color || '#3B82F6'}"></div>
                                    <span class="text-sm text-gray-600 dark:text-gray-400">${colors.find(c => c.value === admin.color)?.name || 'Azul'}</span>
                                </div>
                            </div>
                        </div>
                    `).join('') || '<p class="text-gray-500 col-span-full text-center py-8">Nenhum administrador cadastrado</p>'}
                </div>
            </div>
        `;
        
        window.administratorsData = administrators;
        window.colorOptions = colors;
        
    } catch (error) {
        content.innerHTML = `<div class="text-red-500">Erro ao carregar administradores: ${error.message}</div>`;
    }
}

async function openAdminModal(id = null) {
    const colors = window.colorOptions || [
        { value: '#3B82F6', name: 'Azul' },
        { value: '#22C55E', name: 'Verde' },
        { value: '#EF4444', name: 'Vermelho' },
        { value: '#F59E0B', name: 'Amarelo' },
        { value: '#8B5CF6', name: 'Roxo' },
        { value: '#EC4899', name: 'Rosa' },
        { value: '#14B8A6', name: 'Turquesa' },
        { value: '#F97316', name: 'Laranja' }
    ];
    
    let admin = null;
    if (id) {
        admin = (window.administratorsData || []).find(a => a.id === id);
    }
    
    const modalContent = `
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">${id ? 'Editar' : 'Novo'} Administrador</h3>
            <form id="admin-form" class="space-y-4">
                <input type="hidden" id="admin-id" value="${id || ''}">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Nome *</label>
                    <input type="text" id="admin-name" required class="form-input" value="${admin?.name || ''}" data-testid="input-admin-name">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Email *</label>
                    <input type="email" id="admin-email" required class="form-input" value="${admin?.email || ''}" data-testid="input-admin-email">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Senha ${id ? '(deixe vazio para manter)' : '*'}</label>
                    <input type="password" id="admin-password" ${id ? '' : 'required'} class="form-input" placeholder="••••••••" data-testid="input-admin-password">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Cor de Identificação</label>
                    <div class="flex gap-2 flex-wrap">
                        ${colors.map(c => `
                            <button type="button" onclick="selectAdminColor('${c.value}')" class="w-8 h-8 rounded-full border-2 ${admin?.color === c.value ? 'border-gray-800 dark:border-white' : 'border-transparent'} hover:scale-110 transition-transform" style="background-color: ${c.value}" title="${c.name}" data-color="${c.value}"></button>
                        `).join('')}
                    </div>
                    <input type="hidden" id="admin-color" value="${admin?.color || '#3B82F6'}">
                </div>
                
                <div class="flex justify-end gap-3 pt-4">
                    <button type="button" onclick="closeModal()" class="btn-secondary">Cancelar</button>
                    <button type="submit" class="btn-primary" data-testid="button-save-admin">Salvar</button>
                </div>
            </form>
        </div>
    `;
    
    openModal(modalContent);
    
    document.getElementById('admin-form').onsubmit = async (e) => {
        e.preventDefault();
        await saveAdmin();
    };
}

function selectAdminColor(color) {
    document.getElementById('admin-color').value = color;
    document.querySelectorAll('#modal-content button[data-color]').forEach(btn => {
        btn.classList.remove('border-gray-800', 'dark:border-white');
        btn.classList.add('border-transparent');
        if (btn.dataset.color === color) {
            btn.classList.remove('border-transparent');
            btn.classList.add('border-gray-800', 'dark:border-white');
        }
    });
}

async function saveAdmin() {
    const id = document.getElementById('admin-id').value;
    const data = {
        name: document.getElementById('admin-name').value,
        email: document.getElementById('admin-email').value,
        color: document.getElementById('admin-color').value
    };
    
    const password = document.getElementById('admin-password').value;
    if (password) {
        data.password = password;
    }
    
    try {
        if (id) {
            await apiRequest(`administrators.php?id=${id}`, 'PUT', data);
            showToast('Administrador atualizado com sucesso!');
        } else {
            if (!password) {
                showToast('Senha é obrigatória para novo administrador', 'error');
                return;
            }
            await apiRequest('administrators.php', 'POST', data);
            showToast('Administrador cadastrado com sucesso!');
        }
        closeModal();
        renderAdministrators();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function deleteAdmin(id) {
    if (!confirm('Tem certeza que deseja excluir este administrador?')) return;
    
    try {
        await apiRequest(`administrators.php?id=${id}`, 'DELETE');
        showToast('Administrador excluído com sucesso!');
        renderAdministrators();
    } catch (error) {
        showToast(error.message, 'error');
    }
}
