"use client"; import type React from "react"; import Link from "next/link"; import { useState, useEffect } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; 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 { Calendar as CalendarIcon, RefreshCw } from "lucide-react"; import { useRouter } from "next/navigation"; import { toast } from "@/hooks/use-toast"; import { exceptionsService } from "@/services/exceptionApi.mjs"; // IMPORTAR O COMPONENTE CALENDÁRIO DA SHADCN import { Calendar } from "@/components/ui/calendar"; import { format } from "date-fns"; // Usaremos o date-fns para formatação e comparação de datas import { doctorsService } from "@/services/doctorsApi.mjs"; import Sidebar from "@/components/Sidebar"; type Doctor = { id: string; user_id: string | null; crm: string; crm_uf: string; specialty: string; full_name: string; cpf: string; email: string; phone_mobile: string | null; phone2: string | null; cep: string | null; street: string | null; number: string | null; complement: string | null; neighborhood: string | null; city: string | null; state: string | null; birth_date: string | null; rg: string | null; active: boolean; created_at: string; updated_at: string; created_by: string; updated_by: string | null; max_days_in_advance: number; rating: number | null; } // --- TIPAGEM DA CONSULTA SALVA NO LOCALSTORAGE --- interface LocalStorageAppointment { id: number; patientName: string; doctor: string; specialty: string; date: string; // Data no formato YYYY-MM-DD time: string; // Hora no formato HH:MM status: "agendada" | "confirmada" | "cancelada" | "realizada"; location: string; phone: string; } // Função auxiliar para comparar se duas datas (Date objects) são o mesmo dia const isSameDay = (date1: Date, date2: Date) => { return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate(); }; // --- COMPONENTE PRINCIPAL --- export default function ExceptionPage() { const [allAppointments, setAllAppointments] = useState([]); const router = useRouter(); const [filteredAppointments, setFilteredAppointments] = useState([]); const [isLoading, setIsLoading] = useState(false); const [loggedDoctor, setLoggedDoctor] = useState(); const [tipo, setTipo] = useState(""); useEffect(() => { const fetchData = async () => { try { const doctorsList: Doctor[] = await doctorsService.list(); const doctor = doctorsList[0]; // Salva no estado setLoggedDoctor(doctor); } catch (e: any) { alert(`${e?.error} ${e?.message}`); } }; fetchData(); }, []); // NOVO ESTADO 1: Armazena os dias com consultas (para o calendário) const [bookedDays, setBookedDays] = useState([]); // NOVO ESTADO 2: Armazena a data selecionada no calendário const [selectedCalendarDate, setSelectedCalendarDate] = useState(new Date()); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (isLoading) return; //setIsLoading(true); const form = e.currentTarget; const formData = new FormData(form); const apiPayload = { doctor_id: loggedDoctor?.id, created_by: loggedDoctor?.user_id, date: selectedCalendarDate ? format(selectedCalendarDate, "yyyy-MM-dd") : "", start_time: ((formData.get("horarioEntrada")?formData.get("horarioEntrada") + ":00":null) as string) || null, end_time: ((formData.get("horarioSaida")?formData.get("horarioSaida") + ":00":null) as string) || null, kind: tipo || undefined, reason: formData.get("reason"), }; console.log(apiPayload); try { const res = await exceptionsService.create(apiPayload); console.log(res); let message = "Exceção cadastrada 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("/doctor/dashboard"); // adicionar página para listar a disponibilidade } catch (err: any) { toast({ title: "Erro", description: err?.message || "Não foi possível cadastrar a exceção", }); } finally { setIsLoading(false); } }; const displayDate = selectedCalendarDate ? new Date(selectedCalendarDate).toLocaleDateString("pt-BR", { weekday: "long", day: "2-digit", month: "long" }) : "Selecione uma data"; return (

Adicione exceções

Altere a disponibilidade em casos especiais para o Dr. João Silva

Consultas para: {displayDate}

{/* NOVO LAYOUT DE DUAS COLUNAS */}
{/* COLUNA 1: CALENDÁRIO */}
Calendário

Selecione a data desejada.

{/* COLUNA 2: FORM PARA ADICIONAR EXCEÇÃO */}
{isLoading ? (

Carregando a agenda...

) : !selectedCalendarDate ? (

Selecione uma data.

) : (

Dados

)}
); }