"use client"; // Imports mantidos import { useEffect, useState } from "react"; // --- Imports do EventManager (NOVO) - MANTIDOS --- import { EventManager, type Event } from "@/components/features/general/event-manager"; import { v4 as uuidv4 } from 'uuid'; // Usado para IDs de fallback // Imports mantidos import { Button } from "@/components/ui/button"; import "./index.css"; export default function AgendamentoPage() { const [appointments, setAppointments] = useState([]); // REMOVIDO: abas e 3D → não há mais alternância de abas // const [activeTab, setActiveTab] = useState<"calendar" | "3d">("calendar"); // REMOVIDO: estados do 3D e formulário do paciente (eram usados pelo 3D) // const [threeDEvents, setThreeDEvents] = useState([]); // const [showPatientForm, setShowPatientForm] = useState(false); // --- NOVO ESTADO --- // Estado para alimentar o NOVO EventManager com dados da API const [managerEvents, setManagerEvents] = useState([]); const [managerLoading, setManagerLoading] = useState(true); // Padroniza idioma da página para pt-BR (afeta componentes que usam o lang do documento) useEffect(() => { try { // Atributos no document.documentElement.lang = "pt-BR"; document.documentElement.setAttribute("xml:lang", "pt-BR"); document.documentElement.setAttribute("data-lang", "pt-BR"); // Cookie de locale (usado por apps com i18n) const oneYear = 60 * 60 * 24 * 365; document.cookie = `NEXT_LOCALE=pt-BR; Path=/; Max-Age=${oneYear}; SameSite=Lax`; } catch { // ignore } }, []); useEffect(() => { let mounted = true; (async () => { try { setManagerLoading(true); const api = await import('@/lib/api'); const arr = await api.listarAgendamentos('select=*&order=scheduled_at.desc&limit=500').catch(() => []); if (!mounted) return; if (!arr || !arr.length) { setAppointments([]); // REMOVIDO: setThreeDEvents([]) setManagerEvents([]); setManagerLoading(false); return; } const patientIds = Array.from(new Set(arr.map((a: any) => a.patient_id).filter(Boolean))); const patients = (patientIds && patientIds.length) ? await api.buscarPacientesPorIds(patientIds) : []; const patientsById: Record = {}; (patients || []).forEach((p: any) => { if (p && p.id) patientsById[String(p.id)] = p; }); setAppointments(arr || []); // --- LÓGICA DE TRANSFORMAÇÃO PARA O NOVO EVENTMANAGER --- const newManagerEvents: Event[] = (arr || []).map((obj: any) => { const scheduled = obj.scheduled_at || obj.scheduledAt || obj.time || null; const start = scheduled ? new Date(scheduled) : new Date(); const duration = Number(obj.duration_minutes ?? obj.duration ?? 30) || 30; const end = new Date(start.getTime() + duration * 60 * 1000); const patient = (patientsById[String(obj.patient_id)]?.full_name) || obj.patient_name || obj.patient_full_name || obj.patient || 'Paciente'; const title = `${patient}: ${obj.appointment_type ?? obj.type ?? ''}`.trim(); // Mapeamento de cores padronizado const status = String(obj.status || "").toLowerCase(); let color: Event["color"] = "blue"; if (status === "confirmed" || status === "confirmado") color = "green"; else if (status === "pending" || status === "pendente") color = "orange"; else if (status === "canceled" || status === "cancelado" || status === "cancelled") color = "red"; else if (status === "requested" || status === "solicitado") color = "blue"; return { id: obj.id || uuidv4(), title, description: `Agendamento para ${patient}. Status: ${obj.status || 'N/A'}.`, startTime: start, endTime: end, color, }; }); setManagerEvents(newManagerEvents); setManagerLoading(false); // --- FIM DA LÓGICA --- // REMOVIDO: conversão para 3D e setThreeDEvents } catch (err) { console.warn('[AgendamentoPage] falha ao carregar agendamentos', err); setAppointments([]); // REMOVIDO: setThreeDEvents([]) setManagerEvents([]); setManagerLoading(false); } })(); return () => { mounted = false; }; }, []); // Handlers mantidos const handleSaveAppointment = (appointment: any) => { if (appointment.id) { setAppointments((prev) => prev.map((a) => (a.id === appointment.id ? appointment : a)) ); } else { const newAppointment = { ...appointment, id: Date.now().toString(), }; setAppointments((prev) => [...prev, newAppointment]); } }; return (
{/* Cabeçalho simplificado (sem 3D) */}

Calendário

Navegue através do atalho: Calendário (C).

{/* REMOVIDO: botões de abas Calendário/3D */}
{/* Legenda de status (aplica-se ao EventManager) */}
Solicitado
Confirmado
{/* Novo: Cancelado (vermelho) */}
Cancelado
{/* Apenas o EventManager */}
{managerLoading ? (
Conectando ao calendário — carregando agendamentos...
) : (
)}
{/* REMOVIDO: PatientRegistrationForm (era acionado pelo 3D) */}
); }