Dental Care

This commit is contained in:
Iliyan Angelov
2025-11-16 14:29:51 +02:00
commit 39077550ef
194 changed files with 43197 additions and 0 deletions

View File

@@ -0,0 +1,883 @@
"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 (
<Badge variant={variants[status] || "default"} className="text-xs">
{status.toUpperCase()}
</Badge>
);
};
const getPaymentBadge = (status: string) => {
const variants: Record<
string,
"default" | "secondary" | "destructive" | "outline"
> = {
paid: "default",
pending: "secondary",
failed: "destructive",
refunded: "outline",
};
return (
<Badge variant={variants[status] || "default"} className="text-xs">
{status.toUpperCase()}
</Badge>
);
};
const columns: ColumnDef<Appointment>[] = [
{
id: "select",
header: ({ table }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
</div>
),
cell: ({ row }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
</div>
),
enableSorting: false,
enableHiding: false,
},
{
id: "patientName",
accessorFn: (row) => row.patient.name,
header: "Patient",
cell: ({ row }) => (
<div>
<p className="font-medium">{row.original.patient.name}</p>
<p className="text-xs text-muted-foreground">
{row.original.patient.email}
</p>
</div>
),
enableHiding: false,
},
{
id: "dentistName",
accessorFn: (row) => row.dentist.name,
header: "Dentist",
cell: ({ row }) => <span>Dr. {row.original.dentist.name}</span>,
},
{
id: "serviceName",
accessorFn: (row) => row.service.name,
header: "Service",
cell: ({ row }) => row.original.service.name,
},
{
accessorKey: "date",
header: "Date & Time",
cell: ({ row }) => (
<div>
<p>{new Date(row.original.date).toLocaleDateString()}</p>
<p className="text-xs text-muted-foreground">{row.original.timeSlot}</p>
</div>
),
},
{
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: () => <div className="text-right">Amount</div>,
cell: ({ row }) => {
if (row.original.payment) {
const amount = row.original.payment.amount;
return <div className="text-right">{amount.toFixed(2)}</div>;
}
// service.price is a string (e.g., "₱500 ₱1,500" or "₱1,500")
const price = row.original.service.price;
return <div className="text-right">{price}</div>;
},
},
];
type AdminAppointmentsTableProps = {
appointments: Appointment[];
};
export function AdminAppointmentsTable({
appointments,
}: AdminAppointmentsTableProps) {
const router = useRouter();
const [rowSelection, setRowSelection] = React.useState({});
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [sorting, setSorting] = React.useState<SortingState>([]);
const [pagination, setPagination] = React.useState({
pageIndex: 0,
pageSize: 10,
});
const [isLoading, setIsLoading] = React.useState(false);
const [selectedAppointment, setSelectedAppointment] =
React.useState<Appointment | null>(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<Appointment> = {
id: "actions",
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="data-[state=open]:bg-muted text-muted-foreground flex size-8"
size="icon"
disabled={isLoading}
>
<IconDotsVertical />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem
onClick={() => setSelectedAppointment(row.original)}
>
View Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Edit feature coming soon")}
>
Edit
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Reschedule feature coming soon")}
>
Reschedule
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() =>
handleSingleAction(
() => cancelAppointments([row.original.id]),
"cancel appointment"
)
}
>
Cancel
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() =>
handleSingleAction(
() => deleteAppointment(row.original.id),
"delete appointment"
)
}
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
};
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 (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<div className="relative w-full max-w-sm">
<IconSearch className="absolute left-2 top-2.5 size-4 text-muted-foreground" />
<Input
placeholder="Search appointments..."
value={
(table.getColumn("patientName")?.getFilterValue() as string) ?? ""
}
onChange={(event) =>
table.getColumn("patientName")?.setFilterValue(event.target.value)
}
className="pl-8"
/>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<IconLayoutColumns />
<span className="hidden lg:inline">Columns</span>
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{table
.getAllColumns()
.filter(
(column) =>
typeof column.accessorFn !== "undefined" &&
column.getCanHide()
)
.map((column) => {
return (
<DropdownMenuCheckboxItem
key={column.id}
className="capitalize"
checked={column.getIsVisible()}
onCheckedChange={(value) =>
column.toggleVisibility(!!value)
}
>
{column.id}
</DropdownMenuCheckboxItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Bulk Actions Toolbar */}
{table.getFilteredSelectedRowModel().rows.length > 0 && (
<div className="flex items-center gap-2 rounded-lg border bg-muted/50 p-2">
<span className="text-sm font-medium">
{table.getFilteredSelectedRowModel().rows.length} selected
</span>
<div className="ml-auto flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={isLoading}
onClick={() =>
handleBulkAction(confirmAppointments, "confirm appointments")
}
>
Confirm Selected
</Button>
<Button
variant="outline"
size="sm"
disabled={isLoading}
onClick={() => toast.info("Reschedule feature coming soon")}
>
Reschedule Selected
</Button>
<Button
variant="outline"
size="sm"
disabled={isLoading}
onClick={() => toast.info("Send reminders feature coming soon")}
>
Send Reminders
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" disabled={isLoading}>
More Actions
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() =>
handleBulkAction(
completeAppointments,
"complete appointments"
)
}
>
Mark as Completed
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Export feature coming soon")}
>
Export Selected
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() =>
handleBulkAction(cancelAppointments, "cancel appointments")
}
>
Cancel Selected
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() =>
handleBulkAction(deleteAppointments, "delete appointments")
}
>
Delete Selected
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)}
<div className="overflow-hidden rounded-lg border">
<Table>
<TableHeader className="bg-muted">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No appointments found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between">
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="flex w-full items-center gap-8 lg:w-fit">
<div className="hidden items-center gap-2 lg:flex">
<Label htmlFor="rows-per-page" className="text-sm font-medium">
Rows per page
</Label>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
<SelectValue
placeholder={table.getState().pagination.pageSize}
/>
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-fit items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</div>
<div className="ml-auto flex items-center gap-2 lg:ml-0">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<IconChevronsLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<IconChevronLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<IconChevronRight />
</Button>
<Button
variant="outline"
className="hidden size-8 lg:flex"
size="icon"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<IconChevronsRight />
</Button>
</div>
</div>
</div>
{/* Appointment Details Dialog */}
<Dialog
open={!!selectedAppointment}
onOpenChange={() => setSelectedAppointment(null)}
>
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<div className="flex items-start justify-between">
<div>
<DialogTitle className="text-2xl">
Appointment Details
</DialogTitle>
<DialogDescription>
Booking ID: {selectedAppointment?.id}
</DialogDescription>
</div>
{selectedAppointment &&
getStatusBadge(selectedAppointment.status)}
</div>
</DialogHeader>
{selectedAppointment && (
<div className="space-y-6">
{/* Patient Information */}
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Patient Information
</h3>
<div className="grid grid-cols-2 gap-4">
<div className="flex items-start gap-2">
<User className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">
Patient Name
</p>
<p className="font-medium">
{selectedAppointment.patient.name}
</p>
</div>
</div>
<div className="flex items-start gap-2">
<Mail className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">Email</p>
<p className="font-medium text-sm">
{selectedAppointment.patient.email}
</p>
</div>
</div>
</div>
</div>
{/* Service Information */}
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Service Information
</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-sm text-muted-foreground">Service</p>
<p className="font-medium">
{selectedAppointment.service.name}
</p>
</div>
<div>
<p className="text-sm text-muted-foreground">Price</p>
<p className="font-medium">
{formatPrice(selectedAppointment.service.price)}
</p>
</div>
</div>
</div>
{/* Appointment Schedule */}
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Appointment Schedule
</h3>
<div className="grid grid-cols-2 gap-4">
<div className="flex items-start gap-2">
<Calendar className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">Date</p>
<p className="font-medium">
{new Date(selectedAppointment.date).toLocaleDateString(
"en-US",
{
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
}
)}
</p>
</div>
</div>
<div className="flex items-start gap-2">
<Clock className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">Time</p>
<p className="font-medium">
{selectedAppointment.timeSlot}
</p>
</div>
</div>
</div>
</div>
{/* Dentist Information */}
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Assigned Dentist
</h3>
<div className="flex items-center gap-2">
<User className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-sm text-muted-foreground">Dentist</p>
<p className="font-medium">
Dr. {selectedAppointment.dentist.name}
</p>
</div>
</div>
</div>
{/* Payment Information */}
{selectedAppointment.payment && (
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Payment Information
</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-sm text-muted-foreground">
Payment Status
</p>
<div className="mt-1">
{getPaymentBadge(selectedAppointment.payment.status)}
</div>
</div>
<div>
<p className="text-sm text-muted-foreground">Amount</p>
<p className="font-medium">
{selectedAppointment.payment.amount.toLocaleString()}
</p>
</div>
</div>
</div>
)}
{/* Notes */}
{selectedAppointment.notes && (
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Special Requests / Notes
</h3>
<p className="text-sm bg-muted p-3 rounded-lg">
{selectedAppointment.notes}
</p>
</div>
)}
{/* Admin Action Buttons */}
<div className="flex gap-2 pt-4 border-t">
{selectedAppointment.status === "pending" && (
<Button
className="flex-1"
onClick={() => {
const id = selectedAppointment.id;
setSelectedAppointment(null);
handleSingleAction(
() => confirmAppointments([id]),
"confirm appointment"
);
}}
disabled={isLoading}
>
Confirm Appointment
</Button>
)}
{(selectedAppointment.status === "pending" ||
selectedAppointment.status === "confirmed") && (
<>
<Button
variant="outline"
className="flex-1"
onClick={() => {
setSelectedAppointment(null);
toast.info("Reschedule feature coming soon");
}}
>
Reschedule
</Button>
<Button
variant="destructive"
className="flex-1"
onClick={() => {
const id = selectedAppointment.id;
setSelectedAppointment(null);
handleSingleAction(
() => cancelAppointments([id]),
"cancel appointment"
);
}}
disabled={isLoading}
>
Cancel Appointment
</Button>
</>
)}
{selectedAppointment.status === "confirmed" && (
<Button
variant="outline"
className="flex-1"
onClick={() => {
const id = selectedAppointment.id;
setSelectedAppointment(null);
handleSingleAction(
() => completeAppointments([id]),
"mark as completed"
);
}}
disabled={isLoading}
>
Mark as Completed
</Button>
)}
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,807 @@
"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<Dentist>[] = [
{
id: "select",
header: ({ table }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
</div>
),
cell: ({ row }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
</div>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "name",
header: "Name",
cell: ({ row }) => (
<div>
<p className="font-medium">Dr. {row.original.name}</p>
<p className="text-xs text-muted-foreground">{row.original.email}</p>
</div>
),
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 (
<div className="text-sm">
<p>{appointmentCount} total</p>
<p className="text-xs text-muted-foreground">
{completedCount} completed
</p>
</div>
);
},
},
{
accessorKey: "isAvailable",
header: "Status",
cell: ({ row }) => (
<Badge
variant={row.original.isAvailable ? "default" : "secondary"}
className="text-xs"
>
{row.original.isAvailable ? "Available" : "Unavailable"}
</Badge>
),
},
{
accessorKey: "createdAt",
header: "Joined",
cell: ({ row }) => new Date(row.original.createdAt).toLocaleDateString(),
},
{
id: "actions",
cell: () => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="data-[state=open]:bg-muted text-muted-foreground flex size-8"
size="icon"
>
<IconDotsVertical />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem>View Details</DropdownMenuItem>
<DropdownMenuItem>Edit Profile</DropdownMenuItem>
<DropdownMenuItem>View Schedule</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">Deactivate</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
},
];
type AdminDentistsTableProps = {
dentists: Dentist[];
};
export function AdminDentistsTable({ dentists }: AdminDentistsTableProps) {
const [rowSelection, setRowSelection] = React.useState({});
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [sorting, setSorting] = React.useState<SortingState>([]);
const [pagination, setPagination] = React.useState({
pageIndex: 0,
pageSize: 10,
});
const [isLoading, setIsLoading] = React.useState(false);
const [selectedDentist, setSelectedDentist] = React.useState<Dentist | null>(
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<Dentist> = {
id: "actions",
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="data-[state=open]:bg-muted text-muted-foreground flex size-8"
size="icon"
disabled={isLoading}
>
<IconDotsVertical />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem onClick={() => setSelectedDentist(row.original)}>
View Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Edit feature coming soon")}
>
Edit Profile
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Schedule feature coming soon")}
>
View Schedule
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() =>
handleSingleAction(
() =>
updateDentistAvailability(
[row.original.id],
!row.original.isAvailable
),
row.original.isAvailable ? "set unavailable" : "set available"
)
}
>
{row.original.isAvailable ? "Set Unavailable" : "Set Available"}
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => {
if (confirm("Are you sure you want to delete this dentist?")) {
handleSingleAction(
() => deleteDentist(row.original.id),
"delete dentist"
);
}
}}
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
};
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 (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<div className="relative w-full max-w-sm">
<IconSearch className="absolute left-2 top-2.5 size-4 text-muted-foreground" />
<Input
placeholder="Search dentists..."
value={(table.getColumn("name")?.getFilterValue() as string) ?? ""}
onChange={(event) =>
table.getColumn("name")?.setFilterValue(event.target.value)
}
className="pl-8"
/>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<IconLayoutColumns />
<span className="hidden lg:inline">Columns</span>
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{table
.getAllColumns()
.filter(
(column) =>
typeof column.accessorFn !== "undefined" &&
column.getCanHide()
)
.map((column) => {
return (
<DropdownMenuCheckboxItem
key={column.id}
className="capitalize"
checked={column.getIsVisible()}
onCheckedChange={(value) =>
column.toggleVisibility(!!value)
}
>
{column.id}
</DropdownMenuCheckboxItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Bulk Actions Toolbar */}
{table.getFilteredSelectedRowModel().rows.length > 0 && (
<div className="flex items-center gap-2 rounded-lg border bg-muted/50 p-2">
<span className="text-sm font-medium">
{table.getFilteredSelectedRowModel().rows.length} selected
</span>
<div className="ml-auto flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={isLoading}
onClick={() => handleBulkAvailability(true)}
>
Set Available
</Button>
<Button
variant="outline"
size="sm"
disabled={isLoading}
onClick={() => handleBulkAvailability(false)}
>
Set Unavailable
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" disabled={isLoading}>
More Actions
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() =>
toast.info("Send notification feature coming soon")
}
>
Send Notification
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Export feature coming soon")}
>
Export Selected
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Schedule feature coming soon")}
>
View Schedules
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
onClick={() => {
if (
confirm(
"Are you sure you want to deactivate these dentists?"
)
) {
handleBulkAvailability(false);
}
}}
>
Deactivate Selected
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)}
<div className="overflow-hidden rounded-lg border">
<Table>
<TableHeader className="bg-muted">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No dentists found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between">
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="flex w-full items-center gap-8 lg:w-fit">
<div className="hidden items-center gap-2 lg:flex">
<Label htmlFor="rows-per-page" className="text-sm font-medium">
Rows per page
</Label>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
<SelectValue
placeholder={table.getState().pagination.pageSize}
/>
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-fit items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</div>
<div className="ml-auto flex items-center gap-2 lg:ml-0">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<IconChevronsLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<IconChevronLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<IconChevronRight />
</Button>
<Button
variant="outline"
className="hidden size-8 lg:flex"
size="icon"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<IconChevronsRight />
</Button>
</div>
</div>
</div>
{/* Dentist Details Dialog */}
<Dialog
open={!!selectedDentist}
onOpenChange={() => setSelectedDentist(null)}
>
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<div className="flex items-start justify-between">
<div>
<DialogTitle className="text-2xl">Dentist Details</DialogTitle>
<DialogDescription>ID: {selectedDentist?.id}</DialogDescription>
</div>
{selectedDentist && (
<Badge
variant={
selectedDentist.isAvailable ? "default" : "secondary"
}
className="text-xs"
>
{selectedDentist.isAvailable ? "Available" : "Unavailable"}
</Badge>
)}
</div>
</DialogHeader>
{selectedDentist && (
<div className="space-y-6">
{/* Personal Information */}
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Personal Information
</h3>
<div className="grid grid-cols-2 gap-4">
<div className="flex items-start gap-2">
<User className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">Full Name</p>
<p className="font-medium">Dr. {selectedDentist.name}</p>
</div>
</div>
<div className="flex items-start gap-2">
<Mail className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">Email</p>
<p className="font-medium text-sm">
{selectedDentist.email}
</p>
</div>
</div>
{selectedDentist.phone && (
<div className="flex items-start gap-2">
<Phone className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">Phone</p>
<p className="font-medium">{selectedDentist.phone}</p>
</div>
</div>
)}
<div className="flex items-start gap-2">
<Calendar className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">Joined</p>
<p className="font-medium">
{new Date(selectedDentist.createdAt).toLocaleDateString(
"en-US",
{
year: "numeric",
month: "long",
day: "numeric",
}
)}
</p>
</div>
</div>
</div>
</div>
{/* Professional Information */}
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Professional Information
</h3>
<div className="grid grid-cols-2 gap-4">
{selectedDentist.specialization && (
<div className="flex items-start gap-2">
<Award className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">
Specialization
</p>
<p className="font-medium">
{selectedDentist.specialization}
</p>
</div>
</div>
)}
{selectedDentist.experience && (
<div className="flex items-start gap-2">
<Briefcase className="h-5 w-5 text-muted-foreground mt-0.5" />
<div>
<p className="text-sm text-muted-foreground">
Experience
</p>
<p className="font-medium">
{selectedDentist.experience}
</p>
</div>
</div>
)}
</div>
{selectedDentist.qualifications && (
<div className="mt-3">
<p className="text-sm text-muted-foreground mb-1">
Qualifications
</p>
<p className="text-sm bg-muted p-3 rounded-lg">
{selectedDentist.qualifications}
</p>
</div>
)}
</div>
{/* Appointment Statistics */}
<div className="space-y-3">
<h3 className="font-semibold text-lg border-b pb-2">
Appointment Statistics
</h3>
<div className="grid grid-cols-3 gap-4">
<div className="bg-muted p-4 rounded-lg">
<p className="text-2xl font-bold">
{selectedDentist.appointmentsAsDentist.length}
</p>
<p className="text-sm text-muted-foreground">
Total Appointments
</p>
</div>
<div className="bg-muted p-4 rounded-lg">
<p className="text-2xl font-bold">
{
selectedDentist.appointmentsAsDentist.filter(
(apt) => apt.status === "completed"
).length
}
</p>
<p className="text-sm text-muted-foreground">Completed</p>
</div>
<div className="bg-muted p-4 rounded-lg">
<p className="text-2xl font-bold">
{
selectedDentist.appointmentsAsDentist.filter(
(apt) =>
apt.status === "pending" ||
apt.status === "confirmed"
).length
}
</p>
<p className="text-sm text-muted-foreground">Upcoming</p>
</div>
</div>
</div>
{/* Action Buttons */}
<div className="flex gap-2 pt-4 border-t">
<Button
variant="outline"
className="flex-1"
onClick={() => {
setSelectedDentist(null);
toast.info("Edit feature coming soon");
}}
>
Edit Profile
</Button>
<Button
variant="outline"
className="flex-1"
onClick={() => {
setSelectedDentist(null);
toast.info("Schedule feature coming soon");
}}
>
View Schedule
</Button>
<Button
variant={selectedDentist.isAvailable ? "outline" : "default"}
className="flex-1"
onClick={() => {
const id = selectedDentist.id;
const newStatus = !selectedDentist.isAvailable;
setSelectedDentist(null);
handleSingleAction(
() => updateDentistAvailability([id], newStatus),
newStatus ? "set available" : "set unavailable"
);
}}
disabled={isLoading}
>
{selectedDentist.isAvailable
? "Set Unavailable"
: "Set Available"}
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,437 @@
"use client";
import * as React from "react";
import {
IconChevronDown,
IconChevronLeft,
IconChevronRight,
IconChevronsLeft,
IconChevronsRight,
IconDotsVertical,
IconLayoutColumns,
IconSearch,
IconMail,
IconPhone,
} from "@tabler/icons-react";
import {
ColumnDef,
ColumnFiltersState,
flexRender,
getCoreRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
SortingState,
useReactTable,
VisibilityState,
} from "@tanstack/react-table";
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 Patient = {
id: string;
name: string;
email: string;
phone: string | null;
dateOfBirth: Date | null;
medicalHistory: string | null;
createdAt: Date;
appointmentsAsPatient: Array<{
id: string;
status: string;
}>;
payments: Array<{
id: string;
amount: number;
}>;
};
const columns: ColumnDef<Patient>[] = [
{
id: "select",
header: ({ table }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
</div>
),
cell: ({ row }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
</div>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "name",
header: "Name",
cell: ({ row }) => <span className="font-medium">{row.original.name}</span>,
enableHiding: false,
},
{
accessorKey: "contact",
header: "Contact",
cell: ({ row }) => (
<div className="space-y-1">
<div className="flex items-center gap-1 text-sm">
<IconMail className="size-3" />
<span className="text-xs">{row.original.email}</span>
</div>
{row.original.phone && (
<div className="flex items-center gap-1 text-sm">
<IconPhone className="size-3" />
<span className="text-xs">{row.original.phone}</span>
</div>
)}
</div>
),
},
{
accessorKey: "dateOfBirth",
header: "Date of Birth",
cell: ({ row }) =>
row.original.dateOfBirth
? new Date(row.original.dateOfBirth).toLocaleDateString()
: "-",
},
{
accessorKey: "appointments",
header: "Appointments",
cell: ({ row }) => row.original.appointmentsAsPatient.length,
},
{
accessorKey: "totalSpent",
header: () => <div className="text-right">Total Spent</div>,
cell: ({ row }) => {
const totalSpent = row.original.payments.reduce(
(sum, payment) => sum + payment.amount,
0
);
return <div className="text-right">{totalSpent.toFixed(2)}</div>;
},
},
{
accessorKey: "createdAt",
header: "Joined",
cell: ({ row }) => new Date(row.original.createdAt).toLocaleDateString(),
},
{
id: "actions",
cell: () => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="data-[state=open]:bg-muted text-muted-foreground flex size-8"
size="icon"
>
<IconDotsVertical />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem>View Details</DropdownMenuItem>
<DropdownMenuItem>Edit Profile</DropdownMenuItem>
<DropdownMenuItem>View History</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
},
];
type AdminPatientsTableProps = {
patients: Patient[];
};
export function AdminPatientsTable({ patients }: AdminPatientsTableProps) {
const [rowSelection, setRowSelection] = React.useState({});
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [sorting, setSorting] = React.useState<SortingState>([]);
const [pagination, setPagination] = React.useState({
pageIndex: 0,
pageSize: 10,
});
const table = useReactTable({
data: patients,
columns,
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 (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<div className="relative w-full max-w-sm">
<IconSearch className="absolute left-2 top-2.5 size-4 text-muted-foreground" />
<Input
placeholder="Search patients..."
value={(table.getColumn("name")?.getFilterValue() as string) ?? ""}
onChange={(event) =>
table.getColumn("name")?.setFilterValue(event.target.value)
}
className="pl-8"
/>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<IconLayoutColumns />
<span className="hidden lg:inline">Columns</span>
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{table
.getAllColumns()
.filter(
(column) =>
typeof column.accessorFn !== "undefined" &&
column.getCanHide()
)
.map((column) => {
return (
<DropdownMenuCheckboxItem
key={column.id}
className="capitalize"
checked={column.getIsVisible()}
onCheckedChange={(value) =>
column.toggleVisibility(!!value)
}
>
{column.id}
</DropdownMenuCheckboxItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Bulk Actions Toolbar */}
{table.getFilteredSelectedRowModel().rows.length > 0 && (
<div className="flex items-center gap-2 rounded-lg border bg-muted/50 p-2">
<span className="text-sm font-medium">
{table.getFilteredSelectedRowModel().rows.length} selected
</span>
<div className="ml-auto flex items-center gap-2">
<Button variant="outline" size="sm">
Send Email
</Button>
<Button variant="outline" size="sm">
Send SMS
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
More Actions
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>Export Selected</DropdownMenuItem>
<DropdownMenuItem>Add to Group</DropdownMenuItem>
<DropdownMenuItem>Send Appointment Reminder</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">
Delete Selected
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)}
<div className="overflow-hidden rounded-lg border">
<Table>
<TableHeader className="bg-muted">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No patients found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between">
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="flex w-full items-center gap-8 lg:w-fit">
<div className="hidden items-center gap-2 lg:flex">
<Label htmlFor="rows-per-page" className="text-sm font-medium">
Rows per page
</Label>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
<SelectValue
placeholder={table.getState().pagination.pageSize}
/>
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-fit items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</div>
<div className="ml-auto flex items-center gap-2 lg:ml-0">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<IconChevronsLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<IconChevronLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<IconChevronRight />
</Button>
<Button
variant="outline"
className="hidden size-8 lg:flex"
size="icon"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<IconChevronsRight />
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,572 @@
"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<Service>[] = [
{
id: "select",
header: ({ table }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
</div>
),
cell: ({ row }) => (
<div className="flex items-center justify-center">
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
</div>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "name",
header: "Service Name",
cell: ({ row }) => (
<div>
<p className="font-medium">{row.original.name}</p>
<p className="text-xs text-muted-foreground line-clamp-1">
{row.original.description}
</p>
</div>
),
enableHiding: false,
},
{
accessorKey: "category",
header: "Category",
cell: ({ row }) => (
<Badge variant="outline" className="text-xs">
{row.original.category}
</Badge>
),
},
{
accessorKey: "duration",
header: "Duration",
cell: ({ row }) => `${row.original.duration} mins`,
},
{
accessorKey: "price",
header: () => <div className="text-right">Price</div>,
cell: ({ row }) => (
<div className="text-right font-medium">
{row.original.price || "N/A"}
</div>
),
},
{
accessorKey: "bookings",
header: "Bookings",
cell: ({ row }) => row.original.appointments.length,
},
{
accessorKey: "isActive",
header: "Status",
cell: ({ row }) => (
<Badge
variant={row.original.isActive ? "default" : "secondary"}
className="text-xs"
>
{row.original.isActive ? "Active" : "Inactive"}
</Badge>
),
},
];
type AdminServicesTableProps = {
services: Service[];
};
export function AdminServicesTable({ services }: AdminServicesTableProps) {
const router = useRouter();
const [rowSelection, setRowSelection] = React.useState({});
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [sorting, setSorting] = React.useState<SortingState>([]);
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<Service> = {
id: "actions",
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="data-[state=open]:bg-muted text-muted-foreground flex size-8"
size="icon"
disabled={isLoading}
>
<IconDotsVertical />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem
onClick={() => toast.info("Edit feature coming soon")}
>
Edit Service
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
handleServiceAction(
() => duplicateService(row.original.id),
"duplicate service"
)
}
>
Duplicate
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() =>
handleServiceAction(
() =>
updateServiceStatus(
[row.original.id],
!row.original.isActive
),
"toggle service status"
)
}
>
{row.original.isActive ? "Deactivate" : "Activate"}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
onClick={() =>
handleServiceAction(
() => deleteService(row.original.id),
"delete service"
)
}
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
};
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 (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<div className="relative w-full max-w-sm">
<IconSearch className="absolute left-2 top-2.5 size-4 text-muted-foreground" />
<Input
placeholder="Search services..."
value={(table.getColumn("name")?.getFilterValue() as string) ?? ""}
onChange={(event) =>
table.getColumn("name")?.setFilterValue(event.target.value)
}
className="pl-8"
/>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<IconLayoutColumns />
<span className="hidden lg:inline">Columns</span>
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{table
.getAllColumns()
.filter(
(column) =>
typeof column.accessorFn !== "undefined" &&
column.getCanHide()
)
.map((column) => {
return (
<DropdownMenuCheckboxItem
key={column.id}
className="capitalize"
checked={column.getIsVisible()}
onCheckedChange={(value) =>
column.toggleVisibility(!!value)
}
>
{column.id}
</DropdownMenuCheckboxItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
{/* Bulk Actions Toolbar */}
{table.getFilteredSelectedRowModel().rows.length > 0 && (
<div className="flex items-center gap-2 rounded-lg border bg-muted/50 p-2">
<span className="text-sm font-medium">
{table.getFilteredSelectedRowModel().rows.length} selected
</span>
<div className="ml-auto flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={isLoading}
onClick={() =>
handleBulkAction(
(ids) => updateServiceStatus(ids, true),
"activate services"
)
}
>
Activate Selected
</Button>
<Button
variant="outline"
size="sm"
disabled={isLoading}
onClick={() =>
handleBulkAction(
(ids) => updateServiceStatus(ids, false),
"deactivate services"
)
}
>
Deactivate Selected
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" disabled={isLoading}>
More Actions
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => toast.info("Duplicate feature coming soon")}
>
Duplicate Selected
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
toast.info("Update prices feature coming soon")
}
>
Update Prices
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => toast.info("Export feature coming soon")}
>
Export Selected
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
onClick={() =>
handleBulkAction(deleteServices, "delete services")
}
>
Delete Selected
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)}
<div className="overflow-hidden rounded-lg border">
<Table>
<TableHeader className="bg-muted">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No services found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between">
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="flex w-full items-center gap-8 lg:w-fit">
<div className="hidden items-center gap-2 lg:flex">
<Label htmlFor="rows-per-page" className="text-sm font-medium">
Rows per page
</Label>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
<SelectValue
placeholder={table.getState().pagination.pageSize}
/>
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-fit items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</div>
<div className="ml-auto flex items-center gap-2 lg:ml-0">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<IconChevronsLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<IconChevronLeft />
</Button>
<Button
variant="outline"
className="size-8"
size="icon"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<IconChevronRight />
</Button>
<Button
variant="outline"
className="hidden size-8 lg:flex"
size="icon"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<IconChevronsRight />
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,749 @@
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
IconBell,
IconBriefcase,
IconKey,
IconShield,
IconUser,
} from "@tabler/icons-react";
import { toast } from "sonner";
import {
getAdminSettings,
updateAdminSettings,
} from "@/lib/actions/settings-actions";
type User = {
id: string;
name: string;
email: string;
role?: string;
};
type AdminSettingsContentProps = {
user: User;
};
export function AdminSettingsContent({}: AdminSettingsContentProps) {
const [isLoading, setIsLoading] = React.useState(false);
// General Settings State
const [clinicName, setClinicName] = React.useState("Dental U-Care");
const [clinicEmail, setClinicEmail] = React.useState("info@dentalucare.com");
const [clinicPhone, setClinicPhone] = React.useState("+1 (555) 123-4567");
const [clinicAddress, setClinicAddress] = React.useState(
"123 Medical Plaza, Suite 100"
);
const [timezone, setTimezone] = React.useState("America/New_York");
// Appointment Settings State
const [appointmentDuration, setAppointmentDuration] = React.useState("60");
const [bufferTime, setBufferTime] = React.useState("15");
const [maxAdvanceBooking, setMaxAdvanceBooking] = React.useState("90");
const [cancellationDeadline, setCancellationDeadline] = React.useState("24");
const [autoConfirmAppointments, setAutoConfirmAppointments] =
React.useState(false);
// Notification Settings State
const [emailNotifications, setEmailNotifications] = React.useState(true);
const [smsNotifications, setSmsNotifications] = React.useState(true);
const [appointmentReminders, setAppointmentReminders] = React.useState(true);
const [reminderHoursBefore, setReminderHoursBefore] = React.useState("24");
const [newBookingNotifications, setNewBookingNotifications] =
React.useState(true);
const [cancellationNotifications, setCancellationNotifications] =
React.useState(true);
// Payment Settings State
const [requirePaymentUpfront, setRequirePaymentUpfront] =
React.useState(false);
const [allowPartialPayment, setAllowPartialPayment] = React.useState(true);
const [depositPercentage, setDepositPercentage] = React.useState("50");
const [acceptCash, setAcceptCash] = React.useState(true);
const [acceptCard, setAcceptCard] = React.useState(true);
const [acceptEWallet, setAcceptEWallet] = React.useState(true);
// Security Settings State
const [twoFactorAuth, setTwoFactorAuth] = React.useState(false);
const [sessionTimeout, setSessionTimeout] = React.useState("60");
const [passwordExpiry, setPasswordExpiry] = React.useState("90");
const [loginAttempts, setLoginAttempts] = React.useState("5");
// Load settings on mount
React.useEffect(() => {
const loadSettings = async () => {
try {
const settings = await getAdminSettings();
if (settings) {
setClinicName(settings.clinicName);
setClinicEmail(settings.clinicEmail);
setClinicPhone(settings.clinicPhone);
setClinicAddress(settings.clinicAddress);
setTimezone(settings.timezone);
setAppointmentDuration(settings.appointmentDuration);
setBufferTime(settings.bufferTime);
setMaxAdvanceBooking(settings.maxAdvanceBooking);
setCancellationDeadline(settings.cancellationDeadline);
setAutoConfirmAppointments(settings.autoConfirmAppointments);
setEmailNotifications(settings.emailNotifications);
setSmsNotifications(settings.smsNotifications);
setAppointmentReminders(settings.appointmentReminders);
setReminderHoursBefore(settings.reminderHoursBefore);
setNewBookingNotifications(settings.newBookingNotifications);
setCancellationNotifications(settings.cancellationNotifications);
setRequirePaymentUpfront(settings.requirePaymentUpfront);
setAllowPartialPayment(settings.allowPartialPayment);
setDepositPercentage(settings.depositPercentage);
setAcceptCash(settings.acceptCash);
setAcceptCard(settings.acceptCard);
setAcceptEWallet(settings.acceptEWallet);
setTwoFactorAuth(settings.twoFactorAuth);
setSessionTimeout(settings.sessionTimeout);
setPasswordExpiry(settings.passwordExpiry);
setLoginAttempts(settings.loginAttempts);
}
} catch (error) {
console.error("Failed to load admin settings:", error);
toast.error("Failed to load settings");
}
};
loadSettings();
}, []);
const handleSaveGeneral = async () => {
setIsLoading(true);
try {
const result = await updateAdminSettings({
clinicName,
clinicEmail,
clinicPhone,
clinicAddress,
timezone,
});
if (result.success) {
toast.success(result.message);
} else {
toast.error(result.message);
}
} catch (error) {
toast.error("Failed to save general settings");
console.error(error);
} finally {
setIsLoading(false);
}
};
const handleSaveAppointments = async () => {
setIsLoading(true);
try {
const result = await updateAdminSettings({
appointmentDuration,
bufferTime,
maxAdvanceBooking,
cancellationDeadline,
autoConfirmAppointments,
});
if (result.success) {
toast.success(result.message);
} else {
toast.error(result.message);
}
} catch (error) {
toast.error("Failed to save appointment settings");
console.error(error);
} finally {
setIsLoading(false);
}
};
const handleSaveNotifications = async () => {
setIsLoading(true);
try {
const result = await updateAdminSettings({
emailNotifications,
smsNotifications,
appointmentReminders,
reminderHoursBefore,
newBookingNotifications,
cancellationNotifications,
});
if (result.success) {
toast.success(result.message);
} else {
toast.error(result.message);
}
} catch (error) {
toast.error("Failed to save notification settings");
console.error(error);
} finally {
setIsLoading(false);
}
};
const handleSavePayments = async () => {
setIsLoading(true);
try {
const result = await updateAdminSettings({
requirePaymentUpfront,
allowPartialPayment,
depositPercentage,
acceptCash,
acceptCard,
acceptEWallet,
});
if (result.success) {
toast.success(result.message);
} else {
toast.error(result.message);
}
} catch (error) {
toast.error("Failed to save payment settings");
console.error(error);
} finally {
setIsLoading(false);
}
};
const handleSaveSecurity = async () => {
setIsLoading(true);
try {
const result = await updateAdminSettings({
twoFactorAuth,
sessionTimeout,
passwordExpiry,
loginAttempts,
});
if (result.success) {
toast.success(result.message);
} else {
toast.error(result.message);
}
} catch (error) {
toast.error("Failed to save security settings");
console.error(error);
} finally {
setIsLoading(false);
}
};
return (
<div className="flex flex-1 flex-col gap-4 p-4 md:gap-6 md:p-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">Admin Settings</h1>
<p className="text-sm text-muted-foreground">
Manage your clinic settings and preferences
</p>
</div>
</div>
<Tabs defaultValue="general" className="space-y-4">
<TabsList className="grid w-full grid-cols-2 lg:grid-cols-5">
<TabsTrigger value="general" className="gap-2">
<IconBriefcase className="size-4" />
<span className="hidden sm:inline">General</span>
</TabsTrigger>
<TabsTrigger value="appointments" className="gap-2">
<IconUser className="size-4" />
<span className="hidden sm:inline">Appointments</span>
</TabsTrigger>
<TabsTrigger value="notifications" className="gap-2">
<IconBell className="size-4" />
<span className="hidden sm:inline">Notifications</span>
</TabsTrigger>
<TabsTrigger value="payments" className="gap-2">
<IconKey className="size-4" />
<span className="hidden sm:inline">Payments</span>
</TabsTrigger>
<TabsTrigger value="security" className="gap-2">
<IconShield className="size-4" />
<span className="hidden sm:inline">Security</span>
</TabsTrigger>
</TabsList>
{/* General Settings */}
<TabsContent value="general" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Clinic Information</CardTitle>
<CardDescription>
Update your clinic&apos;s basic information and contact details
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="clinic-name">Clinic Name</Label>
<Input
id="clinic-name"
value={clinicName}
onChange={(e) => setClinicName(e.target.value)}
placeholder="Dental U-Care"
/>
</div>
<div className="space-y-2">
<Label htmlFor="clinic-email">Email Address</Label>
<Input
id="clinic-email"
type="email"
value={clinicEmail}
onChange={(e) => setClinicEmail(e.target.value)}
placeholder="info@dentalucare.com"
/>
</div>
<div className="space-y-2">
<Label htmlFor="clinic-phone">Phone Number</Label>
<Input
id="clinic-phone"
value={clinicPhone}
onChange={(e) => setClinicPhone(e.target.value)}
placeholder="+1 (555) 123-4567"
/>
</div>
<div className="space-y-2">
<Label htmlFor="timezone">Timezone</Label>
<Select value={timezone} onValueChange={setTimezone}>
<SelectTrigger id="timezone">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="America/New_York">
Eastern Time (ET)
</SelectItem>
<SelectItem value="America/Chicago">
Central Time (CT)
</SelectItem>
<SelectItem value="America/Denver">
Mountain Time (MT)
</SelectItem>
<SelectItem value="America/Los_Angeles">
Pacific Time (PT)
</SelectItem>
<SelectItem value="Asia/Manila">
Philippine Time (PHT)
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="clinic-address">Clinic Address</Label>
<Textarea
id="clinic-address"
value={clinicAddress}
onChange={(e) => setClinicAddress(e.target.value)}
placeholder="123 Medical Plaza, Suite 100"
rows={3}
/>
</div>
<div className="flex justify-end">
<Button onClick={handleSaveGeneral} disabled={isLoading}>
{isLoading ? "Saving..." : "Save Changes"}
</Button>
</div>
</CardContent>
</Card>
</TabsContent>
{/* Appointment Settings */}
<TabsContent value="appointments" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Appointment Configuration</CardTitle>
<CardDescription>
Manage appointment durations, booking limits, and scheduling
rules
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="appointment-duration">
Default Duration (minutes)
</Label>
<Select
value={appointmentDuration}
onValueChange={setAppointmentDuration}
>
<SelectTrigger id="appointment-duration">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="30">30 minutes</SelectItem>
<SelectItem value="45">45 minutes</SelectItem>
<SelectItem value="60">60 minutes</SelectItem>
<SelectItem value="90">90 minutes</SelectItem>
<SelectItem value="120">120 minutes</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="buffer-time">Buffer Time (minutes)</Label>
<Select value={bufferTime} onValueChange={setBufferTime}>
<SelectTrigger id="buffer-time">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="0">No buffer</SelectItem>
<SelectItem value="10">10 minutes</SelectItem>
<SelectItem value="15">15 minutes</SelectItem>
<SelectItem value="20">20 minutes</SelectItem>
<SelectItem value="30">30 minutes</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="max-advance">
Maximum Advance Booking (days)
</Label>
<Input
id="max-advance"
type="number"
value={maxAdvanceBooking}
onChange={(e) => setMaxAdvanceBooking(e.target.value)}
min="1"
max="365"
/>
</div>
<div className="space-y-2">
<Label htmlFor="cancellation-deadline">
Cancellation Deadline (hours)
</Label>
<Input
id="cancellation-deadline"
type="number"
value={cancellationDeadline}
onChange={(e) => setCancellationDeadline(e.target.value)}
min="1"
max="72"
/>
</div>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Auto-confirm Appointments</Label>
<p className="text-sm text-muted-foreground">
Automatically confirm new bookings without manual review
</p>
</div>
<Switch
checked={autoConfirmAppointments}
onCheckedChange={setAutoConfirmAppointments}
/>
</div>
<div className="flex justify-end">
<Button onClick={handleSaveAppointments} disabled={isLoading}>
{isLoading ? "Saving..." : "Save Changes"}
</Button>
</div>
</CardContent>
</Card>
</TabsContent>
{/* Notification Settings */}
<TabsContent value="notifications" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Notification Preferences</CardTitle>
<CardDescription>
Configure email, SMS, and reminder notifications
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Email Notifications</Label>
<p className="text-sm text-muted-foreground">
Receive notifications via email
</p>
</div>
<Switch
checked={emailNotifications}
onCheckedChange={setEmailNotifications}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>SMS Notifications</Label>
<p className="text-sm text-muted-foreground">
Receive notifications via SMS
</p>
</div>
<Switch
checked={smsNotifications}
onCheckedChange={setSmsNotifications}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Appointment Reminders</Label>
<p className="text-sm text-muted-foreground">
Send reminders to patients before appointments
</p>
</div>
<Switch
checked={appointmentReminders}
onCheckedChange={setAppointmentReminders}
/>
</div>
{appointmentReminders && (
<div className="ml-6 space-y-2">
<Label htmlFor="reminder-hours">
Send reminder (hours before)
</Label>
<Select
value={reminderHoursBefore}
onValueChange={setReminderHoursBefore}
>
<SelectTrigger id="reminder-hours">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="2">2 hours</SelectItem>
<SelectItem value="4">4 hours</SelectItem>
<SelectItem value="12">12 hours</SelectItem>
<SelectItem value="24">24 hours</SelectItem>
<SelectItem value="48">48 hours</SelectItem>
</SelectContent>
</Select>
</div>
)}
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>New Booking Notifications</Label>
<p className="text-sm text-muted-foreground">
Get notified when new appointments are booked
</p>
</div>
<Switch
checked={newBookingNotifications}
onCheckedChange={setNewBookingNotifications}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Cancellation Notifications</Label>
<p className="text-sm text-muted-foreground">
Get notified when appointments are cancelled
</p>
</div>
<Switch
checked={cancellationNotifications}
onCheckedChange={setCancellationNotifications}
/>
</div>
</div>
<div className="flex justify-end">
<Button onClick={handleSaveNotifications} disabled={isLoading}>
{isLoading ? "Saving..." : "Save Changes"}
</Button>
</div>
</CardContent>
</Card>
</TabsContent>
{/* Payment Settings */}
<TabsContent value="payments" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Payment Configuration</CardTitle>
<CardDescription>
Manage payment methods and billing preferences
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Require Payment Upfront</Label>
<p className="text-sm text-muted-foreground">
Require full payment when booking
</p>
</div>
<Switch
checked={requirePaymentUpfront}
onCheckedChange={setRequirePaymentUpfront}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Allow Partial Payment</Label>
<p className="text-sm text-muted-foreground">
Allow patients to pay a deposit
</p>
</div>
<Switch
checked={allowPartialPayment}
onCheckedChange={setAllowPartialPayment}
/>
</div>
{allowPartialPayment && (
<div className="ml-6 space-y-2">
<Label htmlFor="deposit-percentage">
Deposit Percentage
</Label>
<div className="relative">
<Input
id="deposit-percentage"
type="number"
value={depositPercentage}
onChange={(e) => setDepositPercentage(e.target.value)}
min="10"
max="100"
className="pr-8"
/>
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
%
</span>
</div>
</div>
)}
<Separator />
<div className="space-y-3">
<Label>Accepted Payment Methods</Label>
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label className="font-normal">Cash</Label>
<Switch
checked={acceptCash}
onCheckedChange={setAcceptCash}
/>
</div>
<div className="flex items-center justify-between">
<Label className="font-normal">Credit/Debit Card</Label>
<Switch
checked={acceptCard}
onCheckedChange={setAcceptCard}
/>
</div>
<div className="flex items-center justify-between">
<Label className="font-normal">E-Wallet</Label>
<Switch
checked={acceptEWallet}
onCheckedChange={setAcceptEWallet}
/>
</div>
</div>
</div>
</div>
<div className="flex justify-end">
<Button onClick={handleSavePayments} disabled={isLoading}>
{isLoading ? "Saving..." : "Save Changes"}
</Button>
</div>
</CardContent>
</Card>
</TabsContent>
{/* Security Settings */}
<TabsContent value="security" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Security & Privacy</CardTitle>
<CardDescription>
Manage security settings and access controls
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Two-Factor Authentication</Label>
<p className="text-sm text-muted-foreground">
Require 2FA for all admin accounts
</p>
</div>
<Switch
checked={twoFactorAuth}
onCheckedChange={setTwoFactorAuth}
/>
</div>
<Separator />
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="session-timeout">
Session Timeout (minutes)
</Label>
<Input
id="session-timeout"
type="number"
value={sessionTimeout}
onChange={(e) => setSessionTimeout(e.target.value)}
min="15"
max="480"
/>
</div>
<div className="space-y-2">
<Label htmlFor="password-expiry">
Password Expiry (days)
</Label>
<Input
id="password-expiry"
type="number"
value={passwordExpiry}
onChange={(e) => setPasswordExpiry(e.target.value)}
min="30"
max="365"
/>
</div>
<div className="space-y-2">
<Label htmlFor="login-attempts">
Maximum Login Attempts
</Label>
<Input
id="login-attempts"
type="number"
value={loginAttempts}
onChange={(e) => setLoginAttempts(e.target.value)}
min="3"
max="10"
/>
</div>
</div>
</div>
<div className="flex justify-end">
<Button onClick={handleSaveSecurity} disabled={isLoading}>
{isLoading ? "Saving..." : "Save Changes"}
</Button>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
);
}

File diff suppressed because it is too large Load Diff