/**
 * Users Module
 * Gerenciamento de usuários (CRUD, permissões)
 */
const Users = {
    // Dados dos usuários carregados
    data: [],

    // Cache e controle de loading
    _loading: false,
    _lastLoad: 0,
    _cacheTime: 5000, // 5 segundos de cache

    /**
     * Carrega lista de usuários
     * OTIMIZADO: Evita chamadas duplicadas com cache e flag de loading
     */
    async load(force = false) {
        const now = Date.now();

        // Evitar chamadas duplicadas
        if (this._loading) {
            console.log('[Users] Já está carregando, ignorando...');
            return;
        }

        // Usar cache se não forçado e dados recentes
        if (!force && this.data.length > 0 && (now - this._lastLoad) < this._cacheTime) {
            console.log('[Users] Usando cache');
            // Apenas re-renderizar com filtro atual
            const filterSite = document.getElementById('filter-user-site')?.value || '';
            let filtered = this.data;
            if (filterSite === 'super') {
                filtered = this.data.filter(u => !u.site_id);
            }
            this.renderTable(filtered);
            return;
        }

        this._loading = true;
        console.log('[Users] Carregando usuários...');
        const currentUser = Auth.getCurrentUser();

        // Permitir carregar usuários mesmo se não for super_admin (vai mostrar só o próprio)
        const filterSite = document.getElementById('filter-user-site')?.value || '';
        let url = 'users';
        if (filterSite && filterSite !== 'super') {
            url += `&site_id=${filterSite}`;
        }

        try {
            const data = await Api.get(url);

            if (data.status === 'success') {
                this.data = data.data || [];
                this._lastLoad = Date.now();
                console.log('[Users] Usuários carregados:', this.data.length);

                // Filtrar super admins se necessário
                let filtered = this.data;
                if (filterSite === 'super') {
                    filtered = this.data.filter(u => !u.site_id);
                }

                const usersCountEl = document.getElementById('users-count');
                if (usersCountEl) usersCountEl.textContent = this.data.length;
                this.renderTable(filtered);
            }
        } catch (error) {
            console.error('[Users] Erro ao carregar:', error);
        } finally {
            this._loading = false;
        }
    },
    
    /**
     * Renderiza tabela de usuários
     */
    renderTable(users) {
        const tbody = document.getElementById('users-table-body');
        
        if (!users.length) {
            tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">Nenhum usuário encontrado</td></tr>';
            return;
        }
        
        tbody.innerHTML = users.map(user => {
            const roleLabels = {
                'super_admin': '<span class="badge bg-danger">Super Admin</span>',
                'admin': '<span class="badge bg-warning text-dark">Admin</span>',
                'site_admin': '<span class="badge bg-primary">Admin Site</span>',
                'viewer': '<span class="badge bg-secondary">Visualizador</span>'
            };
            
            const statusBadge = user.is_active 
                ? '<span class="badge bg-success">Ativo</span>' 
                : '<span class="badge bg-secondary">Inativo</span>';
            
            const siteInfo = user.site_name 
                ? `<span class="badge bg-info">${user.site_name}</span>` 
                : '<span class="text-muted">-</span>';
            
            const permissions = user.permissions?.length 
                ? user.permissions.map(p => `<small class="badge bg-light text-dark me-1">${this.formatPermission(p)}</small>`).join('') 
                : '<span class="text-muted">-</span>';
            
            const lastLogin = user.last_login 
                ? new Date(user.last_login).toLocaleString('pt-BR') 
                : '<span class="text-muted">Nunca</span>';
            
            return `
                <tr>
                    <td><strong>${user.username}</strong></td>
                    <td><small>${user.email}</small></td>
                    <td>${roleLabels[user.role] || user.role}</td>
                    <td>${siteInfo}</td>
                    <td style="max-width: 200px;">${permissions}</td>
                    <td><small>${lastLogin}</small></td>
                    <td>${statusBadge}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="Users.edit(${user.id})" title="Editar">
                            <i class="fas fa-edit"></i>
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
    },
    
    /**
     * Formata permissão para exibição
     */
    formatPermission(perm) {
        const map = {
            'view_dashboard': '👁️ Painel',
            'view_events': '📊 Eventos',
            'edit_pix': '💳 PIX',
            'view_pix_history': '📜 Hist. PIX',
            'manage_site': '⚙️ Site',
            'all': '🔓 Tudo'
        };
        return map[perm] || perm;
    },
    
    /**
     * Cria novo usuário
     */
    async create() {
        const password = document.getElementById('new-user-password').value;
        const passwordConfirm = document.getElementById('new-user-password-confirm').value;
        
        if (password !== passwordConfirm) {
            alert('As senhas não coincidem!');
            return;
        }
        
        const role = document.getElementById('new-user-role').value;
        const permissions = [];
        
        if (role !== 'super_admin') {
            document.querySelectorAll('#new-user-permissions input:checked').forEach(cb => {
                permissions.push(cb.value);
            });
        }
        
        const userData = {
            username: document.getElementById('new-user-username').value.trim(),
            email: document.getElementById('new-user-email').value.trim(),
            password: password,
            role: role,
            site_id: role === 'super_admin' ? null : parseInt(document.getElementById('new-user-site').value),
            permissions: permissions
        };
        
        try {
            UI.showLoading('Criando usuário...');
            const data = await Api.post('users', userData);
            
            if (data.status === 'success') {
                alert('Usuário criado com sucesso!');
                bootstrap.Modal.getInstance(document.getElementById('modal-new-user')).hide();
                document.getElementById('new-user-form').reset();
                this.load();
            } else {
                alert(data.message || 'Erro ao criar usuário');
            }
        } catch (error) {
            alert('Erro ao criar usuário: ' + error.message);
        } finally {
            UI.hideLoading();
        }
    },
    
    /**
     * Abre modal de edição de usuário
     */
    async edit(userId) {
        try {
            UI.showLoading('Carregando usuário...');
            const data = await Api.get(`user&id=${userId}`);
            
            if (data.status === 'success') {
                const user = data.data;
                
                document.getElementById('edit-user-id').value = user.id;
                document.getElementById('edit-user-username').value = user.username;
                document.getElementById('edit-user-email').value = user.email;
                document.getElementById('edit-user-password').value = '';
                document.getElementById('edit-user-role').value = user.role;
                document.getElementById('edit-user-active').value = user.is_active ? '1' : '0';
                document.getElementById('edit-user-site').value = user.site_id || '';
                
                // Preencher permissões
                document.querySelectorAll('#edit-user-permissions input').forEach(cb => {
                    cb.checked = user.permissions?.includes(cb.value);
                });
                
                this.toggleEditSiteSelector();
                
                new bootstrap.Modal(document.getElementById('modal-edit-user')).show();
            }
        } catch (error) {
            alert('Erro ao carregar usuário');
        } finally {
            UI.hideLoading();
        }
    },
    
    /**
     * Atualiza usuário existente
     */
    async update() {
        const userId = document.getElementById('edit-user-id').value;
        const role = document.getElementById('edit-user-role').value;
        const permissions = [];
        
        if (role !== 'super_admin') {
            document.querySelectorAll('#edit-user-permissions input:checked').forEach(cb => {
                permissions.push(cb.value);
            });
        }
        
        const userData = {
            email: document.getElementById('edit-user-email').value.trim(),
            role: role,
            site_id: role === 'super_admin' ? null : (document.getElementById('edit-user-site').value || null),
            is_active: document.getElementById('edit-user-active').value === '1',
            permissions: permissions
        };
        
        const password = document.getElementById('edit-user-password').value;
        if (password) {
            userData.password = password;
        }
        
        try {
            UI.showLoading('Salvando...');
            const data = await Api.put(`user&id=${userId}`, userData);
            
            if (data.status === 'success') {
                alert('Usuário atualizado com sucesso!');
                bootstrap.Modal.getInstance(document.getElementById('modal-edit-user')).hide();
                this.load();
            } else {
                alert(data.message || 'Erro ao atualizar usuário');
            }
        } catch (error) {
            alert('Erro: ' + error.message);
        } finally {
            UI.hideLoading();
        }
    },
    
    /**
     * Exclui usuário
     */
    async delete() {
        const userId = document.getElementById('edit-user-id').value;
        const username = document.getElementById('edit-user-username').value;
        
        if (!confirm(`Tem certeza que deseja excluir o usuário "${username}"?\n\nEsta ação não pode ser desfeita.`)) {
            return;
        }
        
        try {
            UI.showLoading('Excluindo...');
            const data = await Api.delete(`user&id=${userId}`);
            
            if (data.status === 'success') {
                alert('Usuário excluído com sucesso!');
                bootstrap.Modal.getInstance(document.getElementById('modal-edit-user')).hide();
                this.load();
            } else {
                alert(data.message || 'Erro ao excluir usuário');
            }
        } catch (error) {
            alert('Erro: ' + error.message);
        } finally {
            UI.hideLoading();
        }
    },
    
    /**
     * Toggle do seletor de site no modal de criar
     */
    toggleSiteSelector() {
        const role = document.getElementById('new-user-role').value;
        const container = document.getElementById('new-user-site-container');
        const permContainer = document.getElementById('new-user-permissions-container');
        
        if (role === 'super_admin') {
            container.style.display = 'none';
            permContainer.style.display = 'none';
            document.getElementById('new-user-site').required = false;
        } else {
            container.style.display = '';
            permContainer.style.display = '';
            document.getElementById('new-user-site').required = true;
        }
    },
    
    /**
     * Toggle do seletor de site no modal de editar
     */
    toggleEditSiteSelector() {
        const role = document.getElementById('edit-user-role').value;
        const container = document.getElementById('edit-user-site-container');
        const permContainer = document.getElementById('edit-user-permissions-container');
        
        if (role === 'super_admin') {
            container.style.display = 'none';
            permContainer.style.display = 'none';
        } else {
            container.style.display = '';
            permContainer.style.display = '';
        }
    },
    
    /**
     * Popula os seletores de site nos forms de usuário
     */
    populateSiteSelectors() {
        const sitesData = Sites.getData();
        const newSelect = document.getElementById('new-user-site');
        const editSelect = document.getElementById('edit-user-site');
        const filterSelect = document.getElementById('filter-user-site');
        
        const options = sitesData.map(site => `<option value="${site.id}">${site.name}</option>`).join('');
        
        if (newSelect) newSelect.innerHTML = '<option value="">-- Selecione --</option>' + options;
        if (editSelect) editSelect.innerHTML = '<option value="">-- Nenhum --</option>' + options;
        if (filterSelect) filterSelect.innerHTML = '<option value="">Todos os sites</option><option value="super">Super Admins</option>' + options;
    }
};
