"use client" import { useState } from "react" import { useRouter } from "next/navigation" import Link from "next/link" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Save, Loader2 } from "lucide-react" import ManagerLayout from "@/components/manager-layout" // Mock user service for demonstration. Replace with your actual API service. const usersService = { create: async (payload: any) => { console.log("API Call: Creating user with payload:", payload); // Simulate network delay await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate a success response return { id: Date.now(), ...payload }; // To simulate an error, you could throw an error here: // throw new Error("O e-mail informado já está em uso."); } }; // Define the structure for our form data interface UserFormData { email: string; password: string; nomeCompleto: string; telefone: string; papel: string; // e.g., 'admin', 'gestor', 'medico', etc. } // Define the initial state for the form const defaultFormData: UserFormData = { email: '', password: '', nomeCompleto: '', telefone: '', papel: '', }; // Helper function to remove non-digit characters const cleanNumber = (value: string): string => value.replace(/\D/g, ''); // Helper function to format a phone number const formatPhone = (value: string): string => { const cleaned = cleanNumber(value).substring(0, 11); if (cleaned.length > 10) { return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3'); } return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3'); }; export default function NovoUsuarioPage() { const router = useRouter(); const [formData, setFormData] = useState(defaultFormData); const [isSaving, setIsSaving] = useState(false); const [error, setError] = useState(null); // Handles changes in form inputs const handleInputChange = (key: keyof UserFormData, value: string) => { const updatedValue = key === 'telefone' ? formatPhone(value) : value; setFormData((prev) => ({ ...prev, [key]: updatedValue })); }; // Handles form submission const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); // Basic validation if (!formData.email || !formData.password || !formData.nomeCompleto || !formData.papel) { setError("Por favor, preencha todos os campos obrigatórios."); return; } setIsSaving(true); // Prepare payload for the API const payload = { email: formData.email, password: formData.password, full_name: formData.nomeCompleto, phone: formData.telefone.trim() || null, // Send null if empty role: formData.papel, }; try { await usersService.create(payload); // On success, redirect to the main user list page router.push("/manager/usuario"); } catch (e: any) { console.error("Erro ao criar usuário:", e); setError(e.message || "Ocorreu um erro inesperado. Tente novamente."); } finally { setIsSaving(false); } }; return (

Novo Usuário

Preencha os dados para cadastrar um novo usuário no sistema.

{/* Error Message Display */} {error && (

Erro no Cadastro:

{error}

)}
handleInputChange("nomeCompleto", e.target.value)} placeholder="Nome e Sobrenome" required />
handleInputChange("email", e.target.value)} placeholder="exemplo@dominio.com" required />
handleInputChange("password", e.target.value)} placeholder="••••••••" required />
handleInputChange("telefone", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
{/* Action Buttons */}
); }