import React, { useState, useEffect, useCallback } from 'react'; import { Shield, UserCheck, UserX, Users, Search, RefreshCw, Crown, Eye, User as UserIcon, Info, Image as ImageIcon, Box, Database } from 'lucide-react'; import { clsx } from 'clsx'; import type { AppUser, UserRole } from '../types'; import { useAuth } from '../context/useAuth'; import api from '../services/api'; import { GeometrySettings } from '../components/admin/GeometrySettings'; import { BackupRestore } from '../components/admin/BackupRestore'; const roleLabels: Record = { admin: { label: 'Administrador', color: 'bg-amber-500/20 text-amber-400 border-amber-500/30', icon: }, user: { label: 'Usuário', color: 'bg-primary/20 text-primary border-primary/30', icon: }, guest: { label: 'Convidado', color: 'bg-gray-500/20 text-gray-400 border-gray-500/30', icon: }, }; export const AdminDashboard: React.FC = () => { const { isAdmin, appUser } = useAuth(); const [users, setUsers] = useState([]); const [isLoading, setIsLoading] = useState(true); const [searchTerm, setSearchTerm] = useState(''); const [filterRole, setFilterRole] = useState('all'); const [actionLoading, setActionLoading] = useState(null); const [activeTab, setActiveTab] = useState<'users' | 'organization' | 'settings' | 'stock' | 'backup'>('users'); const fetchUsers = useCallback(async () => { try { setIsLoading(true); const response = await api.get('/users'); setUsers(response.data.map((u: any) => ({ ...u, id: u._id || u.id }))); } catch (error) { console.error('Error fetching users:', error); } finally { setIsLoading(false); } }, []); useEffect(() => { fetchUsers(); }, [fetchUsers]); const handleRoleChange = async (userId: string, newRole: UserRole) => { setActionLoading(userId); try { const response = await api.patch(`/users/${userId}/role`, { role: newRole }); const updated = response.data; setUsers(users.map(u => u.id === userId ? { ...updated, id: updated._id || updated.id } : u)); } catch (error: any) { console.error('Error updating role:', error); alert(error.response?.data?.error || 'Erro ao atualizar role'); } finally { setActionLoading(null); } }; const handleToggleBan = async (userId: string, isBanned: boolean) => { setActionLoading(userId); try { const response = await api.patch(`/users/${userId}/ban`, { isBanned }); const updated = response.data; setUsers(users.map(u => u.id === userId ? { ...updated, id: updated._id || updated.id } : u)); } catch (error: any) { console.error('Error toggling ban:', error); alert(error.response?.data?.error || 'Erro ao alterar status'); } finally { setActionLoading(null); } }; const filteredUsers = users.filter(u => { const matchesSearch = (u.name || '').toLowerCase().includes(searchTerm.toLowerCase()) || (u.email || '').toLowerCase().includes(searchTerm.toLowerCase()); const matchesRole = filterRole === 'all' || u.role === filterRole; return matchesSearch && matchesRole; }); if (!isAdmin()) { return (

Acesso Negado

Você não tem permissão para acessar esta página.

); } return (
{/* Header */}

Administração

Gestão de usuários e configurações do sistema

{activeTab === 'users' && (
)}
{/* Tabs Navigation */}
{activeTab === 'users' ? ( <> {/* Stats */}

{users.length}

Total

{users.filter(u => u.role === 'admin').length}

Admins

{users.filter(u => u.role === 'user').length}

Usuários

{users.filter(u => u.isBanned).length}

Banidos

{/* Filters */}
setSearchTerm(e.target.value)} className="w-full pl-12 pr-4 py-3 bg-surface border border-border/40 rounded-xl text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all" />
{/* Users Table */}
{isLoading ? (
) : filteredUsers.length === 0 ? (

Nenhum usuário encontrado

) : (
{filteredUsers.map((u) => { const roleInfo = roleLabels[u.role]; const isCurrentUser = u.email === appUser?.email; const isActionDisabled = actionLoading === u.id; return ( ); })}
Usuário Email Role Status Ações
{(u.name || u.email || '?').charAt(0).toUpperCase()}

{u.name || 'Sem nome'}

{isCurrentUser && ( (Você) )}
{u.email} {u.isBanned ? ( Banido ) : ( Ativo )} {!isCurrentUser && u.role !== 'admin' && ( )}
)}
) : activeTab === 'settings' ? ( ) : activeTab === 'backup' ? ( ) : (

Em breve

Novas configurações serão adicionadas aqui.

)}
); }; export default AdminDashboard;