"use client" import { useState, useEffect, useCallback } from "react" import { useRouter, useParams } 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 { Textarea } from "@/components/ui/textarea" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Checkbox } from "@/components/ui/checkbox" import { Save, Loader2, ArrowLeft } from "lucide-react" import Sidebar from "@/components/Sidebar" import { doctorsService } from "services/doctorsApi.mjs"; const UF_LIST = ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"]; interface DoctorFormData { nomeCompleto: string; crm: string; crmEstado: string; especialidade: string; cpf: string; email: string; dataNascimento: string; rg: string; telefoneCelular: string; telefone2: string; cep: string; endereco: string; numero: string; complemento: string; bairro: string; cidade: string; estado: string; ativo: boolean; observacoes: string; } const apiMap: { [K in keyof DoctorFormData]: string | null } = { nomeCompleto: 'full_name', crm: 'crm', crmEstado: 'crm_uf', especialidade: 'specialty', cpf: 'cpf', email: 'email', dataNascimento: 'birth_date', rg: 'rg', telefoneCelular: 'phone_mobile', telefone2: 'phone2', cep: 'cep', endereco: 'street', numero: 'number', complemento: 'complement', bairro: 'neighborhood', cidade: 'city', estado: 'state', ativo: 'active', observacoes: null, }; const defaultFormData: DoctorFormData = { nomeCompleto: '', crm: '', crmEstado: '', especialidade: '', cpf: '', email: '', dataNascimento: '', rg: '', telefoneCelular: '', telefone2: '', cep: '', endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '', ativo: true, observacoes: '', }; 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})/, '($1) $2-$3'); } return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3'); }; export default function EditarMedicoPage() { const router = useRouter(); const params = useParams(); const id = Array.isArray(params.id) ? params.id[0] : params.id; const [formData, setFormData] = useState(defaultFormData); const [loading, setLoading] = useState(true); const [isSaving, setIsSaving] = useState(false); const [error, setError] = useState(null); const apiToFormMap: { [key: string]: keyof DoctorFormData } = { 'full_name': 'nomeCompleto', 'crm': 'crm', 'crm_uf': 'crmEstado', 'specialty': 'especialidade', 'cpf': 'cpf', 'email': 'email', 'birth_date': 'dataNascimento', 'rg': 'rg', 'phone_mobile': 'telefoneCelular', 'phone2': 'telefone2', 'cep': 'cep', 'street': 'endereco', 'number': 'numero', 'complement': 'complemento', 'neighborhood': 'bairro', 'city': 'cidade', 'state': 'estado', 'active': 'ativo' }; useEffect(() => { if (!id) return; const fetchDoctor = async () => { try { const data = await doctorsService.getById(id); if (!data) { setError("Médico não encontrado."); setLoading(false); return; } const initialData: Partial = {}; Object.keys(data).forEach(key => { const formKey = apiToFormMap[key]; if (formKey) { let value = data[key] === null ? '' : data[key]; if (formKey === 'ativo') { value = !!value; } else if (typeof value !== 'boolean') { value = String(value); } initialData[formKey] = value as any; } }); initialData.observacoes = "Observação carregada do sistema (exemplo de campo interno)"; setFormData(prev => ({ ...prev, ...initialData })); } catch (e) { console.error("Erro ao carregar dados:", e); setError("Não foi possível carregar os dados do médico."); } finally { setLoading(false); } }; fetchDoctor(); }, [id]); const handleInputChange = (key: keyof DoctorFormData, value: string | boolean) => { if (typeof value === 'string') { let maskedValue = value; if (key === 'cpf') maskedValue = formatCPF(value); if (key === 'cep') maskedValue = formatCEP(value); if (key === 'telefoneCelular' || key === 'telefone2') maskedValue = formatPhoneMobile(value); setFormData((prev) => ({ ...prev, [key]: maskedValue })); } else { setFormData((prev) => ({ ...prev, [key]: value })); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); setIsSaving(true); if (!id) { setError("ID do médico ausente."); setIsSaving(false); return; } const finalPayload: { [key: string]: any } = {}; const formKeys = Object.keys(formData) as Array; formKeys.forEach((key) => { const apiFieldName = apiMap[key]; if (!apiFieldName) return; let value = formData[key]; if (typeof value === 'string') { let trimmedValue = value.trim(); if (trimmedValue === '') { finalPayload[apiFieldName] = null; return; } if (key === 'crmEstado' || key === 'estado') { trimmedValue = trimmedValue.toUpperCase(); } value = trimmedValue; } finalPayload[apiFieldName] = value; }); delete finalPayload.user_id; try { await doctorsService.update(id, finalPayload); router.push("/manager/home"); } catch (e: any) { console.error("Erro ao salvar o médico:", e); let detailedError = "Erro ao atualizar. Verifique os dados e tente novamente."; if (e.message && e.message.includes("duplicate key value violates unique constraint")) { detailedError = "O CPF ou CRM informado já está cadastrado em outro registro."; } else if (e.message && e.message.includes("Detalhes:")) { detailedError = e.message.split("Detalhes:")[1].trim(); } else if (e.message) { detailedError = e.message; } setError(`Erro ao atualizar. Detalhes: ${detailedError}`); } finally { setIsSaving(false); } }; if (loading) { return (

Carregando dados do médico...

); } return (

Editar Médico: {formData.nomeCompleto}

Atualize as informações do médico

{error && (

Erro na Atualização:

{error}

)}

Dados Principais e Pessoais

handleInputChange("nomeCompleto", e.target.value)} placeholder="Nome do Médico" />
handleInputChange("crm", e.target.value)} placeholder="Ex: 123456" />
handleInputChange("especialidade", e.target.value)} placeholder="Ex: Cardiologia" />
handleInputChange("cpf", e.target.value)} placeholder="000.000.000-00" maxLength={14} />
handleInputChange("rg", e.target.value)} placeholder="00.000.000-0" />
handleInputChange("email", e.target.value)} placeholder="exemplo@dominio.com" />
handleInputChange("dataNascimento", e.target.value)} />
handleInputChange("ativo", checked === true)} />

Contato e Endereço

handleInputChange("telefoneCelular", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
handleInputChange("telefone2", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
handleInputChange("cep", e.target.value)} placeholder="00000-000" maxLength={9} />
handleInputChange("endereco", e.target.value)} placeholder="Rua, Avenida, etc." />
handleInputChange("numero", e.target.value)} placeholder="123" />
handleInputChange("complemento", e.target.value)} placeholder="Apto, Bloco, etc." />
handleInputChange("bairro", e.target.value)} placeholder="Bairro" />
handleInputChange("cidade", e.target.value)} placeholder="São Paulo" />
handleInputChange("estado", e.target.value)} placeholder="SP" />

Observações (Apenas internas)