"use client"; import { useState } from "react"; import { X, AlertCircle, CheckCircle, Loader, Eye, EyeOff } from "lucide-react"; interface CadastroSuperadminModalProps { isOpen: boolean; onClose: () => void; onSuccess?: () => void; currentCompanyId?: string; } // Funções de máscara const maskCPF = (value: string): string => { return value .replace(/\D/g, "") .slice(0, 11) .replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4") .replace(/(\d{3})(\d{3})(\d{3})$/, "$1.$2.$3") .replace(/(\d{3})(\d{3})$/, "$1.$2"); }; const maskPhone = (value: string): string => { return value .replace(/\D/g, "") .slice(0, 11) .replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3") .replace(/(\d{2})(\d{4})$/, "($1) $2"); }; export default function CadastroSuperadminModal({ isOpen, onClose, onSuccess, currentCompanyId, }: CadastroSuperadminModalProps) { const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [success, setSuccess] = useState(false); const [showPassword, setShowPassword] = useState(false); const [showConfirmPassword, setShowConfirmPassword] = useState(false); const [formData, setFormData] = useState({ nome: "", email: "", telefone: "", senha: "", confirmaSenha: "", cpf: "", nomeSocial: "", }); const handleChange = (e: React.ChangeEvent) => { const { name, value } = e.target; let formattedValue = value; // Aplicar máscaras if (name === "cpf") { formattedValue = maskCPF(value); } else if (name === "telefone") { formattedValue = maskPhone(value); } setFormData((prev) => ({ ...prev, [name]: formattedValue, })); }; const validarFormulario = (): boolean => { if (!formData.nome.trim()) { setError("Nome é obrigatório"); return false; } if (!formData.email.trim()) { setError("Email é obrigatório"); return false; } if (!formData.email.includes("@")) { setError("Email inválido"); return false; } if (!formData.senha) { setError("Senha é obrigatória"); return false; } if (formData.senha.length < 6) { setError("Senha deve ter pelo menos 6 caracteres"); return false; } if (formData.senha !== formData.confirmaSenha) { setError("As senhas não coincidem"); return false; } if (!formData.cpf.trim()) { setError("CPF é obrigatório"); return false; } // Remover máscara para validar CPF const cpfLimpo = formData.cpf.replace(/\D/g, ""); if (cpfLimpo.length !== 11) { setError("CPF deve ter 11 dígitos"); return false; } return true; }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(""); if (!validarFormulario()) { return; } setLoading(true); try { // Remover máscaras antes de enviar const cpfLimpo = formData.cpf.replace(/\D/g, ""); const telefoneLimpo = formData.telefone.replace(/\D/g, ""); const payload = { name: formData.nome, username: formData.email, email: formData.email, password: formData.senha, cpf: cpfLimpo, superadmin: true, role: "superadmin", "nome-social": formData.nomeSocial || null, company_id: currentCompanyId || "00000000-0000-0000-0000-000000000000", // Fallback if no company provided, though might fail if foreign key invalid }; // Obter token do localStorage para enviar autorização const token = localStorage.getItem('access_token'); const response = await fetch( `${process.env.NEXT_PUBLIC_BFF_API_URL}/users`, { method: "POST", headers: { "accept": "application/json", "Content-Type": "application/json", ...(token && { "Authorization": `Bearer ${token}` }), }, body: JSON.stringify(payload), } ); if (response.ok) { setSuccess(true); setFormData({ nome: "", email: "", telefone: "", senha: "", confirmaSenha: "", cpf: "", nomeSocial: "", }); // Fechar modal após 2 segundos setTimeout(() => { setSuccess(false); onClose(); onSuccess?.(); }, 2000); } else { const errorData = await response.json().catch(() => ({})); setError( errorData.message || errorData.error || `Erro ao criar superadmin (${response.status})` ); } } catch (err) { console.error("Erro ao criar superadmin:", err); setError("Erro ao conectar com o servidor"); } finally { setLoading(false); } }; if (!isOpen) return null; return (
{/* Header */}

Cadastrar Superadmin

{/* Conteúdo */}
{success ? (

Sucesso!

Superadmin cadastrado com sucesso

) : (
{/* Mensagem de Erro */} {error && (

{error}

)} {/* Nome */}
{/* Email */}
{/* CPF */}
{/* Telefone */}
{/* Nome Social */}
{/* Senha */}
{/* Confirmar Senha */}
{/* Botões */}
)}
); }