"use client"; import * as React from "react"; import { IconChevronDown, IconChevronLeft, IconChevronRight, IconChevronsLeft, IconChevronsRight, IconDotsVertical, IconLayoutColumns, IconSearch, } from "@tabler/icons-react"; import { toast } from "sonner"; import { useRouter } from "next/navigation"; import { updateServiceStatus, deleteServices, deleteService, duplicateService, } 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"; type Service = { id: string; name: string; description: string; duration: number; price: string; category: string; isActive: boolean; createdAt: Date; appointments: Array<{ id: 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: "Service Name", cell: ({ row }) => (

{row.original.name}

{row.original.description}

), enableHiding: false, }, { accessorKey: "category", header: "Category", cell: ({ row }) => ( {row.original.category} ), }, { accessorKey: "duration", header: "Duration", cell: ({ row }) => `${row.original.duration} mins`, }, { accessorKey: "price", header: () =>
Price
, cell: ({ row }) => (
{row.original.price || "N/A"}
), }, { accessorKey: "bookings", header: "Bookings", cell: ({ row }) => row.original.appointments.length, }, { accessorKey: "isActive", header: "Status", cell: ({ row }) => ( {row.original.isActive ? "Active" : "Inactive"} ), }, ]; type AdminServicesTableProps = { services: Service[]; }; export function AdminServicesTable({ services }: AdminServicesTableProps) { 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 handleServiceAction = 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 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 services 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 actionsColumn: ColumnDef = { id: "actions", cell: ({ row }) => ( toast.info("Edit feature coming soon")} > Edit Service handleServiceAction( () => duplicateService(row.original.id), "duplicate service" ) } > Duplicate handleServiceAction( () => updateServiceStatus( [row.original.id], !row.original.isActive ), "toggle service status" ) } > {row.original.isActive ? "Deactivate" : "Activate"} handleServiceAction( () => deleteService(row.original.id), "delete service" ) } > Delete ), }; const columnsWithActions = [...columns, actionsColumn]; const table = useReactTable({ data: services, 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("Duplicate feature coming soon")} > Duplicate Selected toast.info("Update prices feature coming soon") } > Update Prices toast.info("Export feature coming soon")} > Export Selected handleBulkAction(deleteServices, "delete services") } > 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 services found. )}
{table.getFilteredSelectedRowModel().rows.length} of{" "} {table.getFilteredRowModel().rows.length} row(s) selected.
Page {table.getState().pagination.pageIndex + 1} of{" "} {table.getPageCount()}
); }