'use client'; import { useEffect, useState } from 'react'; import { useRouter } from 'next/navigation'; import Header from '@/components/Header'; import { Users, Search, RefreshCw, ChevronLeft, ChevronRight, Check, X, User, Calendar, Mail, Phone, Hash, Shield, ShieldCheck } from 'lucide-react'; import { useUsuariosApi } from '@/hooks/useUsuariosApi'; import { UsuarioBff } from '@/services/usuarioApiService'; const GestaoUsuarios = () => { const router = useRouter(); const [user, setUser] = useState(null); const [searchTerm, setSearchTerm] = useState(''); const [checkingAuth, setCheckingAuth] = useState(true); const { usuarios, loading, error, totalUsuarios, currentPage, totalPages, listarUsuarios, setCurrentPage, limparErro, } = useUsuariosApi(); useEffect(() => { const checkAuth = async () => { try { // Verificar se há token armazenado const storedToken = localStorage.getItem('access_token'); if (!storedToken) { router.push("/login"); return; } // Buscar dados do usuário da API BFF const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/auth/me`, { method: "GET", headers: { "accept": "application/json", "Authorization": `Bearer ${storedToken}`, }, }); if (response.ok) { const userData = await response.json(); setUser(userData); } else { localStorage.removeItem('access_token'); router.push("/login"); return; } } catch (error) { console.error('❌ Erro ao verificar autenticação:', error); localStorage.removeItem('access_token'); router.push('/login'); } finally { setCheckingAuth(false); } }; checkAuth(); }, [router]); // Carregar usuários quando a autenticação for concluída useEffect(() => { if (user && !checkingAuth) { listarUsuarios({ page: 1 }).then(() => { }).catch((error) => { console.error("❌ Erro ao carregar usuários:", error); }); } }, [user, checkingAuth, listarUsuarios]); // Tela de carregamento durante verificação de autenticação if (checkingAuth) { return (

Verificando autenticação...

); } if (!user) { return (

Verificando autenticação...

); } const handleSearch = async () => { limparErro(); await listarUsuarios({ page: 1, search: searchTerm.trim() || undefined }); }; const handleRefresh = async () => { limparErro(); await listarUsuarios({ page: currentPage, search: searchTerm.trim() || undefined }); }; const handlePrevPage = async () => { if (currentPage > 1) { const newPage = currentPage - 1; setCurrentPage(newPage); await listarUsuarios({ page: newPage, search: searchTerm.trim() || undefined }); } }; const handleNextPage = async () => { if (currentPage < totalPages) { const newPage = currentPage + 1; setCurrentPage(newPage); await listarUsuarios({ page: newPage, search: searchTerm.trim() || undefined }); } }; const formatDate = (dateString: string) => { return new Date(dateString).toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', }); }; const getStatusBadge = (usuario: UsuarioBff) => { if (usuario.superadmin) { return ( Super Admin ); } if (usuario.ativo) { return ( Ativo ); } return ( Inativo ); }; const getRegistroStatusBadge = (registroCompleto: boolean) => { if (registroCompleto) { return ( Completo ); } return ( Incompleto ); }; return (
{/* Cabeçalho da seção */}

Lista de Usuários

{totalUsuarios} usuários encontrados

{/* Controles de busca */}
setSearchTerm(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { handleSearch(); } }} className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
{/* Mensagem de erro */} {error && (

Erro ao carregar usuários

{error}

)} {/* Tabela de usuários */}
{loading ? (
Carregando usuários...
) : usuarios.length === 0 ? (

Nenhum usuário encontrado

{searchTerm ? 'Tente ajustar os termos da busca' : 'Não há usuários cadastrados'}

) : ( <> {/* Tabela desktop */}
{usuarios.map((usuario) => ( ))}
Usuário Contato Status Registro Criado em
{usuario.nome || usuario.nome_social || 'Nome não informado'}
{usuario.identificador}
{usuario.cpf && (
CPF: {usuario.cpf}
)}
{usuario.email && (
{usuario.email}
)} {usuario.telefone && (
{usuario.telefone}
)} {!usuario.email && !usuario.telefone && ( Não informado )}
{getStatusBadge(usuario)} {usuario.nivel && ( {usuario.nivel} )}
{getRegistroStatusBadge(usuario.registro_completo)}
{formatDate(usuario.createdAt)}
{/* Cards mobile */}
{usuarios.map((usuario) => (

{usuario.nome || usuario.nome_social || 'Nome não informado'}

{usuario.identificador}

{getStatusBadge(usuario)} {getRegistroStatusBadge(usuario.registro_completo)}
{usuario.email && (

{usuario.email}

)} {usuario.telefone && (

{usuario.telefone}

)} {usuario.cpf && (

CPF: {usuario.cpf}

)}

{formatDate(usuario.createdAt)}

))}
{/* Paginação */} {totalPages > 1 && (

Mostrando{' '} {((currentPage - 1) * 20) + 1} {' '} até{' '} {Math.min(currentPage * 20, totalUsuarios)} {' '} de{' '} {totalUsuarios} usuários

)} )}
); }; export default GestaoUsuarios;