"use client"; import * as React from "react"; import { IconChevronDown, IconChevronLeft, IconChevronRight, IconChevronsLeft, IconChevronsRight, IconDotsVertical, IconLayoutColumns, IconSearch, } from "@tabler/icons-react"; import { Calendar, Clock, User, Mail } from "lucide-react"; import { toast } from "sonner"; import { useRouter } from "next/navigation"; import { confirmAppointments, cancelAppointments, completeAppointments, deleteAppointments, deleteAppointment, } from "@/lib/actions/admin-actions"; import { ColumnDef, ColumnFiltersState, flexRender, getCoreRowModel, getFacetedRowModel, getFacetedUniqueValues, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, SortingState, useReactTable, VisibilityState, } from "@tanstack/react-table"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; type Appointment = { id: string; date: Date; timeSlot: string; status: string; notes: string | null; patient: { name: string; email: string; }; dentist: { name: string; }; service: { name: string; price: string; }; payment: { status: string; amount: number; } | null; }; const getStatusBadge = (status: string) => { const variants: Record< string, "default" | "secondary" | "destructive" | "outline" > = { pending: "secondary", confirmed: "default", cancelled: "destructive", completed: "outline", rescheduled: "secondary", }; return ( {status.toUpperCase()} ); }; const getPaymentBadge = (status: string) => { const variants: Record< string, "default" | "secondary" | "destructive" | "outline" > = { paid: "default", pending: "secondary", failed: "destructive", refunded: "outline", }; return ( {status.toUpperCase()} ); }; const columns: ColumnDef[] = [ { id: "select", header: ({ table }) => (
table.toggleAllPageRowsSelected(!!value)} aria-label="Select all" />
), cell: ({ row }) => (
row.toggleSelected(!!value)} aria-label="Select row" />
), enableSorting: false, enableHiding: false, }, { id: "patientName", accessorFn: (row) => row.patient.name, header: "Patient", cell: ({ row }) => (

{row.original.patient.name}

{row.original.patient.email}

), enableHiding: false, }, { id: "dentistName", accessorFn: (row) => row.dentist.name, header: "Dentist", cell: ({ row }) => Dr. {row.original.dentist.name}, }, { id: "serviceName", accessorFn: (row) => row.service.name, header: "Service", cell: ({ row }) => row.original.service.name, }, { accessorKey: "date", header: "Date & Time", cell: ({ row }) => (

{new Date(row.original.date).toLocaleDateString()}

{row.original.timeSlot}

), }, { accessorKey: "status", header: "Status", cell: ({ row }) => getStatusBadge(row.original.status), }, { id: "paymentStatus", accessorFn: (row) => row.payment?.status || "none", header: "Payment", cell: ({ row }) => row.original.payment ? getPaymentBadge(row.original.payment.status) : "-", }, { accessorKey: "amount", header: () =>
Amount
, cell: ({ row }) => { if (row.original.payment) { const amount = row.original.payment.amount; return
₱{amount.toFixed(2)}
; } // service.price is a string (e.g., "₱500 – ₱1,500" or "₱1,500") const price = row.original.service.price; return
{price}
; }, }, ]; type AdminAppointmentsTableProps = { appointments: Appointment[]; }; export function AdminAppointmentsTable({ appointments, }: AdminAppointmentsTableProps) { const router = useRouter(); const [rowSelection, setRowSelection] = React.useState({}); const [columnVisibility, setColumnVisibility] = React.useState({}); const [columnFilters, setColumnFilters] = React.useState( [] ); const [sorting, setSorting] = React.useState([]); const [pagination, setPagination] = React.useState({ pageIndex: 0, pageSize: 10, }); const [isLoading, setIsLoading] = React.useState(false); const [selectedAppointment, setSelectedAppointment] = React.useState(null); const formatPrice = (price: number | string): string => { if (typeof price === "string") { return price; } if (isNaN(price)) { return "Contact for pricing"; } return `₱${price.toLocaleString()}`; }; const handleBulkAction = async ( action: (ids: string[]) => Promise<{ success: boolean; message: string }>, actionName: string ) => { const selectedRows = table.getFilteredSelectedRowModel().rows; const ids = selectedRows.map((row) => row.original.id); if (ids.length === 0) { toast.error("No appointments selected"); return; } setIsLoading(true); try { const result = await action(ids); if (result.success) { toast.success(result.message); setRowSelection({}); router.refresh(); } else { toast.error(result.message); } } catch (error) { toast.error(`Failed to ${actionName}`); console.error(error); } finally { setIsLoading(false); } }; const handleSingleAction = async ( action: () => Promise<{ success: boolean; message: string }>, actionName: string ) => { setIsLoading(true); try { const result = await action(); if (result.success) { toast.success(result.message); router.refresh(); } else { toast.error(result.message); } } catch (error) { toast.error(`Failed to ${actionName}`); console.error(error); } finally { setIsLoading(false); } }; const actionsColumn: ColumnDef = { id: "actions", cell: ({ row }) => ( setSelectedAppointment(row.original)} > View Details toast.info("Edit feature coming soon")} > Edit toast.info("Reschedule feature coming soon")} > Reschedule handleSingleAction( () => cancelAppointments([row.original.id]), "cancel appointment" ) } > Cancel handleSingleAction( () => deleteAppointment(row.original.id), "delete appointment" ) } > Delete ), }; const columnsWithActions = [...columns, actionsColumn]; const table = useReactTable({ data: appointments, columns: columnsWithActions, state: { sorting, columnVisibility, rowSelection, columnFilters, pagination, }, enableRowSelection: true, onRowSelectionChange: setRowSelection, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onPaginationChange: setPagination, getCoreRowModel: getCoreRowModel(), getFilteredRowModel: getFilteredRowModel(), getPaginationRowModel: getPaginationRowModel(), getSortedRowModel: getSortedRowModel(), getFacetedRowModel: getFacetedRowModel(), getFacetedUniqueValues: getFacetedUniqueValues(), }); return (
table.getColumn("patientName")?.setFilterValue(event.target.value) } className="pl-8" />
{table .getAllColumns() .filter( (column) => typeof column.accessorFn !== "undefined" && column.getCanHide() ) .map((column) => { return ( column.toggleVisibility(!!value) } > {column.id} ); })}
{/* Bulk Actions Toolbar */} {table.getFilteredSelectedRowModel().rows.length > 0 && (
{table.getFilteredSelectedRowModel().rows.length} selected
handleBulkAction( completeAppointments, "complete appointments" ) } > Mark as Completed toast.info("Export feature coming soon")} > Export Selected handleBulkAction(cancelAppointments, "cancel appointments") } > Cancel Selected handleBulkAction(deleteAppointments, "delete appointments") } > Delete Selected
)}
{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => { return ( {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} ); })} ))} {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( {row.getVisibleCells().map((cell) => ( {flexRender( cell.column.columnDef.cell, cell.getContext() )} ))} )) ) : ( No appointments found. )}
{table.getFilteredSelectedRowModel().rows.length} of{" "} {table.getFilteredRowModel().rows.length} row(s) selected.
Page {table.getState().pagination.pageIndex + 1} of{" "} {table.getPageCount()}
{/* Appointment Details Dialog */} setSelectedAppointment(null)} >
Appointment Details Booking ID: {selectedAppointment?.id}
{selectedAppointment && getStatusBadge(selectedAppointment.status)}
{selectedAppointment && (
{/* Patient Information */}

Patient Information

Patient Name

{selectedAppointment.patient.name}

Email

{selectedAppointment.patient.email}

{/* Service Information */}

Service Information

Service

{selectedAppointment.service.name}

Price

{formatPrice(selectedAppointment.service.price)}

{/* Appointment Schedule */}

Appointment Schedule

Date

{new Date(selectedAppointment.date).toLocaleDateString( "en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric", } )}

Time

{selectedAppointment.timeSlot}

{/* Dentist Information */}

Assigned Dentist

Dentist

Dr. {selectedAppointment.dentist.name}

{/* Payment Information */} {selectedAppointment.payment && (

Payment Information

Payment Status

{getPaymentBadge(selectedAppointment.payment.status)}

Amount

₱{selectedAppointment.payment.amount.toLocaleString()}

)} {/* Notes */} {selectedAppointment.notes && (

Special Requests / Notes

{selectedAppointment.notes}

)} {/* Admin Action Buttons */}
{selectedAppointment.status === "pending" && ( )} {(selectedAppointment.status === "pending" || selectedAppointment.status === "confirmed") && ( <> )} {selectedAppointment.status === "confirmed" && ( )}
)}
); }