"use client"; import * as React from "react"; import { IconChevronDown, IconChevronLeft, IconChevronRight, IconChevronsLeft, IconChevronsRight, IconDotsVertical, IconLayoutColumns, IconSearch, } from "@tabler/icons-react"; import { User, Mail, Phone, Calendar, Award, Briefcase } from "lucide-react"; import { toast } from "sonner"; import { updateDentistAvailability, deleteDentist, } 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 Dentist = { id: string; name: string; email: string; phone: string | null; specialization: string | null; qualifications: string | null; experience: string | null; isAvailable: boolean; createdAt: Date; appointmentsAsDentist: Array<{ id: string; status: string; }>; }; 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, }, { accessorKey: "name", header: "Name", cell: ({ row }) => (

Dr. {row.original.name}

{row.original.email}

), enableHiding: false, }, { accessorKey: "specialization", header: "Specialization", cell: ({ row }) => row.original.specialization || "-", }, { accessorKey: "experience", header: "Experience", cell: ({ row }) => row.original.experience || "-", }, { accessorKey: "appointments", header: "Appointments", cell: ({ row }) => { const appointmentCount = row.original.appointmentsAsDentist.length; const completedCount = row.original.appointmentsAsDentist.filter( (apt) => apt.status === "completed" ).length; return (

{appointmentCount} total

{completedCount} completed

); }, }, { accessorKey: "isAvailable", header: "Status", cell: ({ row }) => ( {row.original.isAvailable ? "Available" : "Unavailable"} ), }, { accessorKey: "createdAt", header: "Joined", cell: ({ row }) => new Date(row.original.createdAt).toLocaleDateString(), }, { id: "actions", cell: () => ( View Details Edit Profile View Schedule Deactivate ), }, ]; type AdminDentistsTableProps = { dentists: Dentist[]; }; export function AdminDentistsTable({ dentists }: AdminDentistsTableProps) { 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 [selectedDentist, setSelectedDentist] = React.useState( null ); const handleBulkAvailability = async (isAvailable: boolean) => { const selectedRows = table.getFilteredSelectedRowModel().rows; const ids = selectedRows.map((row) => row.original.id); if (ids.length === 0) { toast.error("No dentists selected"); return; } setIsLoading(true); try { const result = await updateDentistAvailability(ids, isAvailable); if (result.success) { toast.success(result.message); setRowSelection({}); window.location.reload(); } else { toast.error(result.message); } } catch (error) { toast.error(`Failed to update availability`); 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); window.location.reload(); } 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 }) => ( setSelectedDentist(row.original)}> View Details toast.info("Edit feature coming soon")} > Edit Profile toast.info("Schedule feature coming soon")} > View Schedule handleSingleAction( () => updateDentistAvailability( [row.original.id], !row.original.isAvailable ), row.original.isAvailable ? "set unavailable" : "set available" ) } > {row.original.isAvailable ? "Set Unavailable" : "Set Available"} { if (confirm("Are you sure you want to delete this dentist?")) { handleSingleAction( () => deleteDentist(row.original.id), "delete dentist" ); } }} > Delete ), }; const columnsWithActions = [...columns.slice(0, -1), actionsColumn]; const table = useReactTable({ data: dentists, 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("name")?.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
toast.info("Send notification feature coming soon") } > Send Notification toast.info("Export feature coming soon")} > Export Selected toast.info("Schedule feature coming soon")} > View Schedules { if ( confirm( "Are you sure you want to deactivate these dentists?" ) ) { handleBulkAvailability(false); } }} > Deactivate 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 dentists found. )}
{table.getFilteredSelectedRowModel().rows.length} of{" "} {table.getFilteredRowModel().rows.length} row(s) selected.
Page {table.getState().pagination.pageIndex + 1} of{" "} {table.getPageCount()}
{/* Dentist Details Dialog */} setSelectedDentist(null)} >
Dentist Details ID: {selectedDentist?.id}
{selectedDentist && ( {selectedDentist.isAvailable ? "Available" : "Unavailable"} )}
{selectedDentist && (
{/* Personal Information */}

Personal Information

Full Name

Dr. {selectedDentist.name}

Email

{selectedDentist.email}

{selectedDentist.phone && (

Phone

{selectedDentist.phone}

)}

Joined

{new Date(selectedDentist.createdAt).toLocaleDateString( "en-US", { year: "numeric", month: "long", day: "numeric", } )}

{/* Professional Information */}

Professional Information

{selectedDentist.specialization && (

Specialization

{selectedDentist.specialization}

)} {selectedDentist.experience && (

Experience

{selectedDentist.experience}

)}
{selectedDentist.qualifications && (

Qualifications

{selectedDentist.qualifications}

)}
{/* Appointment Statistics */}

Appointment Statistics

{selectedDentist.appointmentsAsDentist.length}

Total Appointments

{ selectedDentist.appointmentsAsDentist.filter( (apt) => apt.status === "completed" ).length }

Completed

{ selectedDentist.appointmentsAsDentist.filter( (apt) => apt.status === "pending" || apt.status === "confirmed" ).length }

Upcoming

{/* Action Buttons */}
)}
); }