"use client"; import type React from "react"; import { useState } from "react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Checkbox } from "@/components/ui/checkbox"; import { Upload, Plus, X, ChevronDown } from "lucide-react"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; import { useToast } from "@/hooks/use-toast"; import SecretaryLayout from "@/components/secretary-layout"; import { patientsService } from "@/services/patientsApi.mjs"; export default function NovoPacientePage() { const [anexosOpen, setAnexosOpen] = useState(false); const [anexos, setAnexos] = useState([]); const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const { toast } = useToast(); const adicionarAnexo = () => { setAnexos([...anexos, `Documento ${anexos.length + 1}`]); }; const removerAnexo = (index: number) => { setAnexos(anexos.filter((_, i) => i !== index)); }; const cleanNumber = (value: string): string => value.replace(/\D/g, ''); const formatCPF = (value: string): string => { const cleaned = cleanNumber(value).substring(0, 11); return cleaned.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4'); }; const formatCEP = (value: string): string => { const cleaned = cleanNumber(value).substring(0, 8); return cleaned.replace(/(\d{5})(\d{3})/, '$1-$2'); }; const formatPhoneMobile = (value: string): string => { const cleaned = cleanNumber(value).substring(0, 11); if (cleaned.length > 10) { return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '+55 ($1) $2-$3'); } return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '+55 ($1) $2-$3'); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (isLoading) return; setIsLoading(true); const form = e.currentTarget; const formData = new FormData(form); const apiPayload = { full_name: (formData.get("nome") as string) || "", // obrigatório social_name: (formData.get("nomeSocial") as string) || undefined, cpf: (formatCPF(formData.get("cpf") as string)) || "", // obrigatório email: (formData.get("email") as string) || "", // obrigatório phone_mobile: (formatPhoneMobile(formData.get("celular") as string)) || "", // obrigatório birth_date: formData.get("dataNascimento") ? new Date(formData.get("dataNascimento") as string) : undefined, sex: (formData.get("sexo") as string) || undefined, blood_type: (formData.get("tipoSanguineo") as string) || undefined, weight_kg: formData.get("peso") ? parseFloat(formData.get("peso") as string) : undefined, height_m: formData.get("altura") ? parseFloat(formData.get("altura") as string) : undefined, cep: (formatCEP(formData.get("cep") as string)) || undefined, street: (formData.get("endereco") as string) || undefined, number: (formData.get("numero") as string) || undefined, complement: (formData.get("complemento") as string) || undefined, neighborhood: (formData.get("bairro") as string) || undefined, city: (formData.get("cidade") as string) || undefined, state: (formData.get("estado") as string) || undefined, }; console.log(apiPayload.email) console.log(apiPayload.cep) console.log(apiPayload.phone_mobile) const errors: string[] = []; const fullName = apiPayload.full_name?.trim() || ""; if (!fullName || fullName.length < 2 || fullName.length > 255) { errors.push("Nome deve ter entre 2 e 255 caracteres."); } const cpf = apiPayload.cpf || ""; if (!/^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(cpf)) { errors.push("CPF deve estar no formato XXX.XXX.XXX-XX."); } const sex = apiPayload.sex; const allowedSex = ["Masculino", "Feminino", "outro"]; if (!sex || !allowedSex.includes(sex)) { errors.push("Sexo é obrigatório e deve ser masculino, feminino ou outro."); } if (!apiPayload.birth_date) { errors.push("Data de nascimento é obrigatória."); } const phoneMobile = apiPayload.phone_mobile || ""; if (phoneMobile && !/^\+55 \(\d{2}\) \d{4,5}-\d{4}$/.test(phoneMobile)) { errors.push("Celular deve estar no formato +55 (XX) XXXXX-XXXX."); } const cep = apiPayload.cep || ""; if (cep && !/^\d{5}-\d{3}$/.test(cep)) { errors.push("CEP deve estar no formato XXXXX-XXX."); } const state = apiPayload.state || ""; if (state && state.length !== 2) { errors.push("Estado (UF) deve ter 2 caracteres."); } if (errors.length) { toast({ title: "Corrija os campos", description: errors[0] }); console.log("campos errados") setIsLoading(false); return; } try { const res = await patientsService.create(apiPayload); console.log(res) let message = "Paciente cadastrado com sucesso"; try { if (!res[0].id) { throw new Error(`${res.error} ${res.message}`|| "A API retornou erro"); } else { console.log(message) } } catch {} toast({ title: "Sucesso", description: message, }); router.push("/secretary/pacientes"); } catch (err: any) { toast({ title: "Erro", description: err?.message || "Não foi possível cadastrar o paciente", }); } finally { setIsLoading(false); } }; return (

Novo Paciente

Cadastre um novo paciente no sistema

Dados Pessoais