forked from RiseUP/riseup-squad21
agendamento dos pacientes
This commit is contained in:
parent
55125f1c44
commit
b791186640
@ -1,288 +1,343 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { toast } from "sonner";
|
||||
import { useAppointments, Appointment } from "../../context/AppointmentsContext";
|
||||
|
||||
// Componentes de UI e Ícones
|
||||
import { useState, useEffect } from "react";
|
||||
import PatientLayout from "@/components/patient-layout";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogClose } from "@/components/ui/dialog";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
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 { Calendar, Clock, MapPin, Phone, CalendarDays, X, Trash2 } from "lucide-react";
|
||||
import { Calendar, Clock, MapPin, Phone, User, X, CalendarDays } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function PatientAppointmentsPage() {
|
||||
const { appointments, updateAppointment, deleteAppointment } = useAppointments();
|
||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
|
||||
// Estados para controlar os modais e os dados do formulário
|
||||
const [isRescheduleModalOpen, setRescheduleModalOpen] = useState(false);
|
||||
const [isCancelModalOpen, setCancelModalOpen] = useState(false);
|
||||
const [selectedAppointment, setSelectedAppointment] = useState<Appointment | null>(null);
|
||||
|
||||
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
||||
const [cancelReason, setCancelReason] = useState("");
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||
|
||||
// --- MANIPULADORES DE EVENTOS ---
|
||||
// Simulação do paciente logado
|
||||
const LOGGED_PATIENT_ID = "P001";
|
||||
|
||||
const handleRescheduleClick = (appointment: Appointment) => {
|
||||
setSelectedAppointment(appointment);
|
||||
// Preenche o formulário com os dados atuais da consulta
|
||||
setRescheduleData({ date: appointment.date, time: appointment.time, reason: appointment.observations || "" });
|
||||
setRescheduleModalOpen(true);
|
||||
};
|
||||
export default function PatientAppointments() {
|
||||
const [appointments, setAppointments] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||
|
||||
const handleCancelClick = (appointment: Appointment) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setCancelReason(""); // Limpa o motivo ao abrir
|
||||
setCancelModalOpen(true);
|
||||
};
|
||||
|
||||
const confirmReschedule = () => {
|
||||
if (!rescheduleData.date || !rescheduleData.time) {
|
||||
toast.error("Por favor, selecione uma nova data e horário");
|
||||
return;
|
||||
}
|
||||
if (selectedAppointment) {
|
||||
updateAppointment(selectedAppointment.id, {
|
||||
date: rescheduleData.date,
|
||||
time: rescheduleData.time,
|
||||
observations: rescheduleData.reason, // Atualiza as observações com o motivo
|
||||
});
|
||||
toast.success("Consulta reagendada com sucesso!");
|
||||
setRescheduleModalOpen(false);
|
||||
}
|
||||
};
|
||||
// Modais
|
||||
const [rescheduleModal, setRescheduleModal] = useState(false);
|
||||
const [cancelModal, setCancelModal] = useState(false);
|
||||
|
||||
const confirmCancel = () => {
|
||||
if (cancelReason.trim().length < 10) {
|
||||
toast.error("Por favor, forneça um motivo com pelo menos 10 caracteres.");
|
||||
return;
|
||||
}
|
||||
if (selectedAppointment) {
|
||||
// Apenas atualiza o status e adiciona o motivo do cancelamento nas observações
|
||||
updateAppointment(selectedAppointment.id, {
|
||||
status: "Cancelada",
|
||||
observations: `Motivo do cancelamento: ${cancelReason}`
|
||||
});
|
||||
toast.success("Consulta cancelada com sucesso!");
|
||||
setCancelModalOpen(false);
|
||||
}
|
||||
};
|
||||
// Formulário de reagendamento/cancelamento
|
||||
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
||||
const [cancelReason, setCancelReason] = useState("");
|
||||
|
||||
const handleDeleteClick = (appointmentId: string) => {
|
||||
if (window.confirm("Tem certeza que deseja excluir permanentemente esta consulta? Esta ação não pode ser desfeita.")) {
|
||||
deleteAppointment(appointmentId);
|
||||
toast.success("Consulta excluída do histórico.");
|
||||
}
|
||||
};
|
||||
const timeSlots = [
|
||||
"08:00",
|
||||
"08:30",
|
||||
"09:00",
|
||||
"09:30",
|
||||
"10:00",
|
||||
"10:30",
|
||||
"11:00",
|
||||
"11:30",
|
||||
"14:00",
|
||||
"14:30",
|
||||
"15:00",
|
||||
"15:30",
|
||||
"16:00",
|
||||
"16:30",
|
||||
"17:00",
|
||||
"17:30",
|
||||
];
|
||||
|
||||
// --- LÓGICA AUXILIAR ---
|
||||
|
||||
const getStatusBadge = (status: Appointment['status']) => {
|
||||
switch (status) {
|
||||
case "Agendada": return <Badge className="bg-blue-100 text-blue-800 font-medium">Agendada</Badge>;
|
||||
case "Realizada": return <Badge className="bg-green-100 text-green-800 font-medium">Realizada</Badge>;
|
||||
case "Cancelada": return <Badge className="bg-red-100 text-red-800 font-medium">Cancelada</Badge>;
|
||||
}
|
||||
};
|
||||
const fetchData = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const [appointmentList, patientList, doctorList] = await Promise.all([
|
||||
appointmentsService.list(),
|
||||
patientsService.list(),
|
||||
doctorsService.list(),
|
||||
]);
|
||||
|
||||
const timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "15:00", "15:30"];
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0); // Zera o horário para comparar apenas o dia
|
||||
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
||||
|
||||
// ETAPA 1: ORDENAÇÃO DAS CONSULTAS
|
||||
// Cria uma cópia do array e o ordena
|
||||
const sortedAppointments = [...appointments].sort((a, b) => {
|
||||
const statusWeight = { 'Agendada': 1, 'Realizada': 2, 'Cancelada': 3 };
|
||||
|
||||
// Primeiro, ordena por status (Agendada vem primeiro)
|
||||
if (statusWeight[a.status] !== statusWeight[b.status]) {
|
||||
return statusWeight[a.status] - statusWeight[b.status];
|
||||
}
|
||||
// Filtra apenas as consultas do paciente logado
|
||||
const patientAppointments = appointmentList
|
||||
.filter((apt: any) => apt.patient_id === LOGGED_PATIENT_ID)
|
||||
.map((apt: any) => ({
|
||||
...apt,
|
||||
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
||||
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
||||
}));
|
||||
|
||||
// Se o status for o mesmo, ordena por data (mais recente/futura no topo)
|
||||
return new Date(b.date).getTime() - new Date(a.date).getTime();
|
||||
});
|
||||
setAppointments(patientAppointments);
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar consultas:", error);
|
||||
toast.error("Não foi possível carregar suas consultas.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PatientLayout>
|
||||
<div className="space-y-8">
|
||||
<div className="flex justify-between items-center">
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "requested":
|
||||
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
||||
case "confirmed":
|
||||
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
||||
case "checked_in":
|
||||
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
||||
case "completed":
|
||||
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||
case "cancelled":
|
||||
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||
default:
|
||||
return <Badge variant="secondary">{status}</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
const handleReschedule = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setRescheduleData({ date: "", time: "", reason: "" });
|
||||
setRescheduleModal(true);
|
||||
};
|
||||
|
||||
const handleCancel = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setCancelReason("");
|
||||
setCancelModal(true);
|
||||
};
|
||||
|
||||
const confirmReschedule = async () => {
|
||||
if (!rescheduleData.date || !rescheduleData.time) {
|
||||
toast.error("Por favor, selecione uma nova data e horário.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const newScheduledAt = new Date(`${rescheduleData.date}T${rescheduleData.time}:00Z`).toISOString();
|
||||
|
||||
await appointmentsService.update(selectedAppointment.id, {
|
||||
scheduled_at: newScheduledAt,
|
||||
status: "requested",
|
||||
});
|
||||
|
||||
setAppointments((prev) =>
|
||||
prev.map((apt) =>
|
||||
apt.id === selectedAppointment.id ? { ...apt, scheduled_at: newScheduledAt, status: "requested" } : apt
|
||||
)
|
||||
);
|
||||
|
||||
setRescheduleModal(false);
|
||||
toast.success("Consulta reagendada com sucesso!");
|
||||
} catch (error) {
|
||||
console.error("Erro ao reagendar consulta:", error);
|
||||
toast.error("Não foi possível reagendar a consulta.");
|
||||
}
|
||||
};
|
||||
|
||||
const confirmCancel = async () => {
|
||||
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
|
||||
toast.error("Por favor, informe um motivo de cancelamento (mínimo 10 caracteres).");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await appointmentsService.update(selectedAppointment.id, {
|
||||
status: "cancelled",
|
||||
cancel_reason: cancelReason,
|
||||
});
|
||||
|
||||
setAppointments((prev) =>
|
||||
prev.map((apt) =>
|
||||
apt.id === selectedAppointment.id ? { ...apt, status: "cancelled" } : apt
|
||||
)
|
||||
);
|
||||
|
||||
setCancelModal(false);
|
||||
toast.success("Consulta cancelada com sucesso!");
|
||||
} catch (error) {
|
||||
console.error("Erro ao cancelar consulta:", error);
|
||||
toast.error("Não foi possível cancelar a consulta.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PatientLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
||||
<p className="text-gray-600">Veja, reagende ou cancele suas consultas</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{isLoading ? (
|
||||
<p>Carregando suas consultas...</p>
|
||||
) : appointments.length > 0 ? (
|
||||
appointments.map((appointment) => (
|
||||
<Card key={appointment.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
||||
<p className="text-gray-600">Histórico e consultas agendadas</p>
|
||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
||||
</div>
|
||||
<Link href="/patient/schedule">
|
||||
<Button className="bg-gray-800 hover:bg-gray-900 text-white">
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Agendar Nova Consulta
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
{getStatusBadge(appointment.status)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-3">
|
||||
<div className="space-y-2 text-sm text-gray-700">
|
||||
<div className="flex items-center">
|
||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: "UTC",
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<MapPin className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{appointment.doctor.location || "Local a definir"}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{appointment.doctor.phone || "N/A"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{/* Utiliza o array ORDENADO para a renderização */}
|
||||
{sortedAppointments.map((appointment) => {
|
||||
const appointmentDate = new Date(appointment.date);
|
||||
let displayStatus = appointment.status;
|
||||
{appointment.status !== "cancelled" && (
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}>
|
||||
<CalendarDays className="mr-2 h-4 w-4" />
|
||||
Reagendar
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||
onClick={() => handleCancel(appointment)}
|
||||
>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
if (appointment.status === 'Agendada' && appointmentDate < today) {
|
||||
displayStatus = 'Realizada';
|
||||
}
|
||||
|
||||
return (
|
||||
<Card key={appointment.id} className="overflow-hidden">
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-xl">{appointment.doctorName}</CardTitle>
|
||||
<CardDescription>{appointment.specialty}</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(displayStatus)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-x-8 gap-y-4 mb-6">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center text-sm text-gray-700">
|
||||
<Calendar className="mr-3 h-4 w-4 text-gray-500" />
|
||||
{new Date(appointment.date).toLocaleDateString("pt-BR", { timeZone: 'UTC' })}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-700">
|
||||
<Clock className="mr-3 h-4 w-4 text-gray-500" />
|
||||
{appointment.time}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center text-sm text-gray-700">
|
||||
<MapPin className="mr-3 h-4 w-4 text-gray-500" />
|
||||
{appointment.location || 'Local não informado'}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-700">
|
||||
<Phone className="mr-3 h-4 w-4 text-gray-500" />
|
||||
{appointment.phone || 'Telefone não informado'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Container ÚNICO para todas as ações */}
|
||||
<div className="flex gap-2 pt-4 border-t">
|
||||
{(displayStatus === "Agendada") && (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => handleRescheduleClick(appointment)}>
|
||||
<CalendarDays className="mr-2 h-4 w-4" />
|
||||
Reagendar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="text-orange-600 hover:text-orange-700 hover:bg-orange-50" onClick={() => handleCancelClick(appointment)}>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
Cancelar
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{(displayStatus === "Realizada" || displayStatus === "Cancelada") && (
|
||||
<Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50" onClick={() => handleDeleteClick(appointment.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Excluir do Histórico
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{/* MODAL DE REAGENDAMENTO */}
|
||||
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reagendar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Escolha uma nova data e horário para sua consulta com{" "}
|
||||
<strong>{selectedAppointment?.doctor?.full_name}</strong>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="date">Nova Data</Label>
|
||||
<Input
|
||||
id="date"
|
||||
type="date"
|
||||
value={rescheduleData.date}
|
||||
onChange={(e) => setRescheduleData((prev) => ({ ...prev, date: e.target.value }))}
|
||||
min={new Date().toISOString().split("T")[0]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ETAPA 2: CONSTRUÇÃO DOS MODAIS */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="time">Novo Horário</Label>
|
||||
<Select
|
||||
value={rescheduleData.time}
|
||||
onValueChange={(value) => setRescheduleData((prev) => ({ ...prev, time: value }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{timeSlots.map((time) => (
|
||||
<SelectItem key={time} value={time}>
|
||||
{time}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="reason">Motivo (opcional)</Label>
|
||||
<Textarea
|
||||
id="reason"
|
||||
placeholder="Explique brevemente o motivo do reagendamento..."
|
||||
value={rescheduleData.reason}
|
||||
onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={confirmReschedule}>Confirmar</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Modal de Reagendamento */}
|
||||
<Dialog open={isRescheduleModalOpen} onOpenChange={setRescheduleModalOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reagendar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Reagendar consulta com {selectedAppointment?.doctorName}.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="date" className="text-right">Nova Data</Label>
|
||||
<Input
|
||||
id="date"
|
||||
type="date"
|
||||
value={rescheduleData.date}
|
||||
onChange={(e) => setRescheduleData({...rescheduleData, date: e.target.value})}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="time" className="text-right">Novo Horário</Label>
|
||||
<Select
|
||||
value={rescheduleData.time}
|
||||
onValueChange={(value) => setRescheduleData({...rescheduleData, time: value})}
|
||||
>
|
||||
<SelectTrigger className="col-span-3">
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{timeSlots.map(time => <SelectItem key={time} value={time}>{time}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="reason" className="text-right">Motivo</Label>
|
||||
<Textarea
|
||||
id="reason"
|
||||
placeholder="Informe o motivo do reagendamento (opcional)"
|
||||
value={rescheduleData.reason}
|
||||
onChange={(e) => setRescheduleData({...rescheduleData, reason: e.target.value})}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">Cancelar</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" onClick={confirmReschedule}>Confirmar Reagendamento</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Modal de Cancelamento */}
|
||||
<Dialog open={isCancelModalOpen} onOpenChange={setCancelModalOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Cancelar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Você tem certeza que deseja cancelar sua consulta com {selectedAppointment?.doctorName}? Esta ação não pode ser desfeita.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<Label htmlFor="cancelReason">Motivo do Cancelamento (obrigatório)</Label>
|
||||
<Textarea
|
||||
id="cancelReason"
|
||||
placeholder="Por favor, descreva o motivo do cancelamento..."
|
||||
value={cancelReason}
|
||||
onChange={(e) => setCancelReason(e.target.value)}
|
||||
className="mt-2"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">Voltar</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" variant="destructive" onClick={confirmCancel}>Confirmar Cancelamento</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</PatientLayout>
|
||||
);
|
||||
}
|
||||
{/* MODAL DE CANCELAMENTO */}
|
||||
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Cancelar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Deseja realmente cancelar sua consulta com{" "}
|
||||
<strong>{selectedAppointment?.doctor?.full_name}</strong>?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cancel-reason" className="text-sm font-medium">
|
||||
Motivo do Cancelamento <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="cancel-reason"
|
||||
placeholder="Informe o motivo do cancelamento (mínimo 10 caracteres)"
|
||||
value={cancelReason}
|
||||
onChange={(e) => setCancelReason(e.target.value)}
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
||||
Voltar
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={confirmCancel}>
|
||||
Confirmar Cancelamento
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</PatientLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
// Importações de componentes omitidas para brevidade, mas estão no código original
|
||||
import { Calendar, Clock, User } from "lucide-react"
|
||||
import PatientLayout from "@/components/patient-layout"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@ -10,49 +9,53 @@ import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Calendar, Clock, User } from "lucide-react"
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
import { doctorsService } from "services/doctorsApi.mjs"
|
||||
|
||||
interface Doctor {
|
||||
id: string;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
phone_mobile: string;
|
||||
|
||||
id: string
|
||||
full_name: string
|
||||
specialty: string
|
||||
phone_mobile: string
|
||||
}
|
||||
|
||||
// Chave do LocalStorage, a mesma usada em secretarypage.tsx
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments"
|
||||
|
||||
export default function ScheduleAppointment() {
|
||||
const [selectedDoctor, setSelectedDoctor] = useState("")
|
||||
const [selectedDate, setSelectedDate] = useState("")
|
||||
const [selectedTime, setSelectedTime] = useState("")
|
||||
const [notes, setNotes] = useState("")
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// novos campos
|
||||
const [tipoConsulta, setTipoConsulta] = useState("presencial")
|
||||
const [duracao, setDuracao] = useState("30")
|
||||
const [convenio, setConvenio] = useState("")
|
||||
const [queixa, setQueixa] = useState("")
|
||||
const [obsPaciente, setObsPaciente] = useState("")
|
||||
const [obsInternas, setObsInternas] = useState("")
|
||||
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
setDoctors(data || []);
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar lista de médicos:", e);
|
||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||
setDoctors([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const data: Doctor[] = await doctorsService.list()
|
||||
setDoctors(data || [])
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar lista de médicos:", e)
|
||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.")
|
||||
setDoctors([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchDoctors();
|
||||
}, [fetchDoctors]);
|
||||
fetchDoctors()
|
||||
}, [fetchDoctors])
|
||||
|
||||
const availableTimes = [
|
||||
"08:00",
|
||||
@ -73,49 +76,54 @@ export default function ScheduleAppointment() {
|
||||
e.preventDefault()
|
||||
|
||||
const doctorDetails = doctors.find((d) => d.id === selectedDoctor)
|
||||
|
||||
// --- SIMULAÇÃO DO PACIENTE LOGADO ---
|
||||
// Você só tem um usuário para cada role. Vamos simular um paciente:
|
||||
const patientDetails = {
|
||||
id: "P001",
|
||||
full_name: "Paciente Exemplo Único", // Este nome aparecerá na agenda do médico
|
||||
location: "Clínica Geral",
|
||||
phone: "(11) 98765-4321"
|
||||
};
|
||||
const patientDetails = {
|
||||
id: "P001",
|
||||
full_name: "Paciente Exemplo Único",
|
||||
location: "Clínica Geral",
|
||||
phone: "(11) 98765-4321",
|
||||
}
|
||||
|
||||
if (!patientDetails || !doctorDetails) {
|
||||
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.");
|
||||
return;
|
||||
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.")
|
||||
return
|
||||
}
|
||||
|
||||
const newAppointment = {
|
||||
id: new Date().getTime(), // ID único simples
|
||||
patientName: patientDetails.full_name,
|
||||
doctor: doctorDetails.full_name, // Nome completo do médico (necessário para a listagem)
|
||||
specialty: doctorDetails.specialty,
|
||||
date: selectedDate,
|
||||
time: selectedTime,
|
||||
status: "agendada",
|
||||
phone: patientDetails.phone,
|
||||
};
|
||||
id: new Date().getTime(),
|
||||
patientName: patientDetails.full_name,
|
||||
doctor: doctorDetails.full_name,
|
||||
specialty: doctorDetails.specialty,
|
||||
date: selectedDate,
|
||||
time: selectedTime,
|
||||
tipoConsulta,
|
||||
duracao,
|
||||
convenio,
|
||||
queixa,
|
||||
obsPaciente,
|
||||
obsInternas,
|
||||
notes,
|
||||
status: "agendada",
|
||||
phone: patientDetails.phone,
|
||||
}
|
||||
|
||||
// 1. Carrega agendamentos existentes
|
||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
||||
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
|
||||
|
||||
// 2. Adiciona o novo agendamento
|
||||
const updatedAppointments = [...currentAppointments, newAppointment];
|
||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY)
|
||||
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : []
|
||||
const updatedAppointments = [...currentAppointments, newAppointment]
|
||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments))
|
||||
|
||||
// 3. Salva a lista atualizada no LocalStorage
|
||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
|
||||
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`)
|
||||
|
||||
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`);
|
||||
|
||||
// Limpar o formulário após o sucesso (opcional)
|
||||
setSelectedDoctor("");
|
||||
setSelectedDate("");
|
||||
setSelectedTime("");
|
||||
setNotes("");
|
||||
// resetar campos
|
||||
setSelectedDoctor("")
|
||||
setSelectedDate("")
|
||||
setSelectedTime("")
|
||||
setNotes("")
|
||||
setTipoConsulta("presencial")
|
||||
setDuracao("30")
|
||||
setConvenio("")
|
||||
setQueixa("")
|
||||
setObsPaciente("")
|
||||
setObsInternas("")
|
||||
}
|
||||
|
||||
return (
|
||||
@ -135,6 +143,9 @@ export default function ScheduleAppointment() {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
|
||||
|
||||
{/* Médico */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="doctor">Médico</Label>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||
@ -142,15 +153,26 @@ export default function ScheduleAppointment() {
|
||||
<SelectValue placeholder="Selecione um médico" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{doctors.map((doctor) => (
|
||||
<SelectItem key={doctor.id} value={doctor.id}>
|
||||
{doctor.full_name} - {doctor.specialty}
|
||||
{loading ? (
|
||||
<SelectItem value="loading" disabled>
|
||||
Carregando médicos...
|
||||
</SelectItem>
|
||||
))}
|
||||
) : error ? (
|
||||
<SelectItem value="error" disabled>
|
||||
Erro ao carregar
|
||||
</SelectItem>
|
||||
) : (
|
||||
doctors.map((doctor) => (
|
||||
<SelectItem key={doctor.id} value={doctor.id}>
|
||||
{doctor.full_name} - {doctor.specialty}
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Data e horário */}
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="date">Data</Label>
|
||||
@ -179,9 +201,81 @@ export default function ScheduleAppointment() {
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
{/* Tipo e Duração */}
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="tipoConsulta">Tipo de Consulta</Label>
|
||||
<Select value={tipoConsulta} onValueChange={setTipoConsulta}>
|
||||
<SelectTrigger id="tipoConsulta">
|
||||
<SelectValue placeholder="Selecione o tipo" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="presencial">Presencial</SelectItem>
|
||||
<SelectItem value="online">Telemedicina</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="duracao">Duração (minutos)</Label>
|
||||
<Input
|
||||
id="duracao"
|
||||
type="number"
|
||||
min={10}
|
||||
max={120}
|
||||
value={duracao}
|
||||
onChange={(e) => setDuracao(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Convênio */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">Observações (opcional)</Label>
|
||||
<Label htmlFor="convenio">Convênio (opcional)</Label>
|
||||
<Input
|
||||
id="convenio"
|
||||
placeholder="Nome do convênio do paciente"
|
||||
value={convenio}
|
||||
onChange={(e) => setConvenio(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Queixa Principal */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="queixa">Queixa Principal (opcional)</Label>
|
||||
<Textarea
|
||||
id="queixa"
|
||||
placeholder="Descreva brevemente o motivo da consulta..."
|
||||
value={queixa}
|
||||
onChange={(e) => setQueixa(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Observações do Paciente */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="obsPaciente">Observações do Paciente (opcional)</Label>
|
||||
<Textarea
|
||||
id="obsPaciente"
|
||||
placeholder="Anotações relevantes informadas pelo paciente..."
|
||||
value={obsPaciente}
|
||||
onChange={(e) => setObsPaciente(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Observações Internas */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="obsInternas">Observações Internas (opcional)</Label>
|
||||
<Textarea
|
||||
id="obsInternas"
|
||||
placeholder="Anotações para a equipe da clínica..."
|
||||
value={obsInternas}
|
||||
onChange={(e) => setObsInternas(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Observações gerais */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">Observações gerais (opcional)</Label>
|
||||
<Textarea
|
||||
id="notes"
|
||||
placeholder="Descreva brevemente o motivo da consulta ou observações importantes"
|
||||
@ -191,7 +285,12 @@ export default function ScheduleAppointment() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={!selectedDoctor || !selectedDate || !selectedTime}>
|
||||
{/* Botão */}
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
||||
>
|
||||
Agendar Consulta
|
||||
</Button>
|
||||
</form>
|
||||
@ -199,6 +298,7 @@ export default function ScheduleAppointment() {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Resumo */}
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@ -211,14 +311,18 @@ export default function ScheduleAppointment() {
|
||||
{selectedDoctor && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<User className="h-4 w-4 text-gray-500" />
|
||||
<span className="text-sm">{doctors.find((d) => d.id === selectedDoctor)?.full_name}</span>
|
||||
<span className="text-sm">
|
||||
{doctors.find((d) => d.id === selectedDoctor)?.full_name}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedDate && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Calendar className="h-4 w-4 text-gray-500" />
|
||||
<span className="text-sm">{new Date(selectedDate).toLocaleDateString("pt-BR")}</span>
|
||||
<span className="text-sm">
|
||||
{new Date(selectedDate).toLocaleDateString("pt-BR")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@ -247,4 +351,4 @@ export default function ScheduleAppointment() {
|
||||
</div>
|
||||
</PatientLayout>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user