"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Calendar, Clock, Video, Search, CalendarCheck, X, Loader2, User, Settings, Check, } from "lucide-react"; import { useAppTheme } from "@/components/ThemeProvider"; import { listAppointments, scheduleAppointment, rejectAppointment } from "@/lib/actions/appointments"; import { useAppointments } from "@/hooks/useAppointments"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { DatePicker } from "@/components/DatePicker"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { toast } from "sonner"; import type { Appointment } from "@/lib/models/appointments"; export default function Booking() { const router = useRouter(); const [appointments, setAppointments] = useState([]); const [loading, setLoading] = useState(true); const [searchTerm, setSearchTerm] = useState(""); const [scheduleDialogOpen, setScheduleDialogOpen] = useState(false); const [rejectDialogOpen, setRejectDialogOpen] = useState(false); const [selectedAppointment, setSelectedAppointment] = useState(null); const [scheduledDate, setScheduledDate] = useState(undefined); const [scheduledTime, setScheduledTime] = useState("09:00"); const [scheduledDuration, setScheduledDuration] = useState(60); const [rejectionReason, setRejectionReason] = useState(""); const [isScheduling, setIsScheduling] = useState(false); const [isRejecting, setIsRejecting] = useState(false); const { theme } = useAppTheme(); const isDark = theme === "dark"; // Availability management const { adminAvailability, isLoadingAdminAvailability, updateAdminAvailability, isUpdatingAvailability } = useAppointments(); const [selectedDays, setSelectedDays] = useState([]); const [availabilityDialogOpen, setAvailabilityDialogOpen] = useState(false); const [startTime, setStartTime] = useState("09:00"); const [endTime, setEndTime] = useState("17:00"); const daysOfWeek = [ { value: 0, label: "Monday" }, { value: 1, label: "Tuesday" }, { value: 2, label: "Wednesday" }, { value: 3, label: "Thursday" }, { value: 4, label: "Friday" }, { value: 5, label: "Saturday" }, { value: 6, label: "Sunday" }, ]; // Initialize selected days when availability is loaded useEffect(() => { if (adminAvailability?.available_days) { setSelectedDays(adminAvailability.available_days); } }, [adminAvailability]); // Generate time slots for time picker const generateTimeSlots = () => { const slots = []; for (let hour = 0; hour < 24; hour++) { for (let minute = 0; minute < 60; minute += 30) { const timeString = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`; slots.push(timeString); } } return slots; }; const timeSlotsForPicker = generateTimeSlots(); const handleDayToggle = (day: number) => { setSelectedDays((prev) => prev.includes(day) ? prev.filter((d) => d !== day) : [...prev, day].sort() ); }; const handleSaveAvailability = async () => { if (selectedDays.length === 0) { toast.error("Please select at least one available day"); return; } if (startTime >= endTime) { toast.error("End time must be after start time"); return; } try { await updateAdminAvailability({ available_days: selectedDays }); toast.success("Availability updated successfully!"); setAvailabilityDialogOpen(false); } catch (error) { console.error("Failed to update availability:", error); const errorMessage = error instanceof Error ? error.message : "Failed to update availability"; toast.error(errorMessage); } }; const handleOpenAvailabilityDialog = () => { if (adminAvailability?.available_days) { setSelectedDays(adminAvailability.available_days); } setAvailabilityDialogOpen(true); }; useEffect(() => { const fetchBookings = async () => { setLoading(true); try { const data = await listAppointments(); setAppointments(data || []); } catch (error) { console.error("Failed to fetch appointments:", error); toast.error("Failed to load appointments. Please try again."); setAppointments([]); } finally { setLoading(false); } }; fetchBookings(); }, []); const formatDate = (dateString: string) => { const date = new Date(dateString); return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", }); }; const formatTime = (dateString: string) => { const date = new Date(dateString); return date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true, }); }; const getStatusColor = (status: string) => { const normalized = status.toLowerCase(); if (isDark) { switch (normalized) { case "scheduled": return "bg-blue-500/20 text-blue-200"; case "completed": return "bg-green-500/20 text-green-200"; case "rejected": case "cancelled": return "bg-red-500/20 text-red-200"; case "pending_review": case "pending": return "bg-yellow-500/20 text-yellow-200"; default: return "bg-gray-700 text-gray-200"; } } switch (normalized) { case "scheduled": return "bg-blue-100 text-blue-700"; case "completed": return "bg-green-100 text-green-700"; case "rejected": case "cancelled": return "bg-red-100 text-red-700"; case "pending_review": case "pending": return "bg-yellow-100 text-yellow-700"; default: return "bg-gray-100 text-gray-700"; } }; const formatStatus = (status: string) => { return status.replace("_", " ").replace(/\b\w/g, (l) => l.toUpperCase()); }; const handleViewDetails = (appointment: Appointment) => { router.push(`/admin/booking/${appointment.id}`); }; const handleScheduleClick = (appointment: Appointment) => { setSelectedAppointment(appointment); setScheduledDate(undefined); setScheduledTime("09:00"); setScheduledDuration(60); setScheduleDialogOpen(true); }; const handleRejectClick = (appointment: Appointment) => { setSelectedAppointment(appointment); setRejectionReason(""); setRejectDialogOpen(true); }; const handleSchedule = async () => { if (!selectedAppointment || !scheduledDate) { toast.error("Please select a date and time"); return; } setIsScheduling(true); try { // Combine date and time into ISO datetime string const [hours, minutes] = scheduledTime.split(":"); const datetime = new Date(scheduledDate); datetime.setHours(parseInt(hours), parseInt(minutes), 0, 0); const isoString = datetime.toISOString(); await scheduleAppointment(selectedAppointment.id, { scheduled_datetime: isoString, scheduled_duration: scheduledDuration, }); toast.success("Appointment scheduled successfully!"); setScheduleDialogOpen(false); // Refresh appointments list const data = await listAppointments(); setAppointments(data || []); } catch (error) { console.error("Failed to schedule appointment:", error); const errorMessage = error instanceof Error ? error.message : "Failed to schedule appointment"; toast.error(errorMessage); } finally { setIsScheduling(false); } }; const handleReject = async () => { if (!selectedAppointment) { return; } setIsRejecting(true); try { await rejectAppointment(selectedAppointment.id, { rejection_reason: rejectionReason || undefined, }); toast.success("Appointment rejected successfully"); setRejectDialogOpen(false); // Refresh appointments list const data = await listAppointments(); setAppointments(data || []); } catch (error) { console.error("Failed to reject appointment:", error); const errorMessage = error instanceof Error ? error.message : "Failed to reject appointment"; toast.error(errorMessage); } finally { setIsRejecting(false); } }; // Generate time slots const timeSlots = []; for (let hour = 8; hour <= 18; hour++) { for (let minute = 0; minute < 60; minute += 30) { const timeString = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`; timeSlots.push(timeString); } } const filteredAppointments = appointments.filter( (appointment) => appointment.first_name .toLowerCase() .includes(searchTerm.toLowerCase()) || appointment.last_name .toLowerCase() .includes(searchTerm.toLowerCase()) || appointment.email.toLowerCase().includes(searchTerm.toLowerCase()) || (appointment.phone && appointment.phone.toLowerCase().includes(searchTerm.toLowerCase())) ); return (
{/* Main Content */}
{/* Page Header */}

Bookings

Manage and view all appointment bookings

{/* Search Bar */}
setSearchTerm(e.target.value)} className={`pl-10 ${isDark ? "bg-gray-800 border-gray-700 text-white placeholder:text-gray-400" : "bg-white border-gray-200 text-gray-900 placeholder:text-gray-500"}`} />
{loading ? (
) : filteredAppointments.length === 0 ? (

No bookings found

{searchTerm ? "Try adjusting your search terms" : "No appointments have been created yet"}

) : (
{filteredAppointments.map((appointment) => ( handleViewDetails(appointment)} > ))}
Patient Status Actions
{appointment.first_name} {appointment.last_name}
{appointment.phone && ( )} {appointment.scheduled_datetime && (
{formatDate(appointment.scheduled_datetime)}
)}
{appointment.scheduled_datetime ? ( <>
{formatDate(appointment.scheduled_datetime)}
{formatTime(appointment.scheduled_datetime)}
) : (
Not scheduled
)}
{formatStatus(appointment.status)}
e.stopPropagation()}> {appointment.status === "pending_review" && ( <> )} {appointment.jitsi_meet_url && ( )}
)}
{/* Schedule Appointment Dialog */} Schedule Appointment {selectedAppointment && ( <>Schedule appointment for {selectedAppointment.first_name} {selectedAppointment.last_name} )}
{/* Reject Appointment Dialog */} Reject Appointment {selectedAppointment && ( <>Reject appointment request from {selectedAppointment.first_name} {selectedAppointment.last_name} )}