// "use client";
// import * as React from "react";
// import {
//   flexRender,
//   getCoreRowModel,
//   getFilteredRowModel,
//   getPaginationRowModel,
//   getSortedRowModel,
//   useReactTable,
// } from "@tanstack/react-table";
// import {
//   ArrowUpDown,
//   ChevronDown,
//   Loader2,
//   MoreHorizontal,
// } from "lucide-react";

// import { Button } from "@/components/ui/button";
// import {
//   DropdownMenu,
//   DropdownMenuCheckboxItem,
//   DropdownMenuContent,
//   DropdownMenuItem,
//   DropdownMenuLabel,
//   DropdownMenuTrigger,
// } from "@/components/ui/dropdown-menu";
// import { Input } from "@/components/ui/input";
// import {
//   Table,
//   TableBody,
//   TableCell,
//   TableHead,
//   TableHeader,
//   TableRow,
// } from "@/components/ui/table";
// import { useQuery, useQueryClient } from "@tanstack/react-query";
// import { useModal } from "@/context/ModalProvider";

// export function DataTable({
//   fetchData,
//   columnsConfig,
//   searchFields,
//   EditComponent = null,
//   onDelete,
//   filters,
//   onView,
//   tag,
// }) {
//   const queryClient = useQueryClient();
//   const { openModal } = useModal();

//   const [sorting, setSorting] = React.useState([]);
//   const [columnFilters, setColumnFilters] = React.useState([]);
//   const [columnVisibility, setColumnVisibility] = React.useState({});
//   const [rowSelection, setRowSelection] = React.useState({});
//   const [pagination, setPagination] = React.useState({
//     pageIndex: 0,
//     pageSize: 10,
//   });

//   // Fetch Data Using React Query
//   const { data: tableData, isLoading } = useQuery({
//     queryKey: [
//       tag,
//       pagination.pageIndex,
//       pagination.pageSize,
//       sorting,
//       filters,
//     ],
//     queryFn: () =>
//       fetchData(pagination.pageIndex, pagination.pageSize, sorting, filters),
//     staleTime: 300000, // 5 minutes
//   });

//   const handleDeleteClick = async (id) => {
//     if (window.confirm("Are you sure you want to delete this item?")) {
//       try {
//         await onDelete(id);
//         queryClient.invalidateQueries([tag]);
//       } catch (error) {
//         console.error("Delete error:", error);
//       }
//     }
//   };
//   const handleEditClick = (row) => {
//     openModal(
//       <EditComponent
//         key={row.original.id}
//         type="edit"
//         editData={row.original}
//       />
//     );
//   };

//   // Define actions column
//   const actionsColumn = {
//     id: "actions",
//     enableHiding: false,
//     cell: ({ row }) => {
//       return (
//         <DropdownMenu>
//           <DropdownMenuTrigger asChild>
//             <Button variant="ghost" className="h-8 w-8 p-0">
//               <span className="sr-only">Open menu</span>
//               <MoreHorizontal className="h-4 w-4" />
//             </Button>
//           </DropdownMenuTrigger>
//           <DropdownMenuContent align="end">
//             <DropdownMenuLabel>Actions</DropdownMenuLabel>
//             {onView && (
//               <DropdownMenuItem onClick={() => onView(row.original)}>
//                 View Details
//               </DropdownMenuItem>
//             )}
//             {EditComponent && (
//               <DropdownMenuItem onClick={() => handleEditClick(row)}>
//                 Edit
//               </DropdownMenuItem>
//             )}
//             {onDelete && (
//               <DropdownMenuItem
//                 onClick={() => handleDeleteClick(row.original.id)}
//                 className="text-red-600"
//               >
//                 Delete
//               </DropdownMenuItem>
//             )}
//           </DropdownMenuContent>
//         </DropdownMenu>
//       );
//     },
//   };

//   // Combine user columns with actions column
//   const columns = [...columnsConfig, actionsColumn];

//   const table = useReactTable({
//     data: tableData?.rows || [],
//     columns,
//     onSortingChange: setSorting,
//     onColumnFiltersChange: setColumnFilters,
//     getCoreRowModel: getCoreRowModel(),
//     getPaginationRowModel: getPaginationRowModel(),
//     getSortedRowModel: getSortedRowModel(),
//     getFilteredRowModel: getFilteredRowModel(),
//     onColumnVisibilityChange: setColumnVisibility,
//      onPaginationChange: setPagination,
//     onRowSelectionChange: setRowSelection,
//     state: {
//       pagination,
//       sorting,
//       columnFilters,
//       columnVisibility,
//       rowSelection,
//     },
//   });

//   if (isLoading) {
//     return (
//       <div className="flex items-center justify-center h-48">
//         <Loader2 className="h-8 w-8 animate-spin" />
//       </div>
//     );
//   }

//   return (
//     <div className="w-full">
//       <div className="flex items-center py-4">
//         {searchFields && (
//           <Input
//             placeholder={`Search ${searchFields}...`}
//             value={table.getColumn(searchFields)?.getFilterValue() ?? ""}
//             onChange={(event) =>
//               table.getColumn(searchFields)?.setFilterValue(event.target.value)
//             }
//             className="max-w-sm"
//           />
//         )}
//         <DropdownMenu>
//           <DropdownMenuTrigger asChild>
//             <Button variant="outline" className="ml-auto">
//               Columns <ChevronDown />
//             </Button>
//           </DropdownMenuTrigger>
//           <DropdownMenuContent align="end">
//             {table
//               .getAllColumns()
//               .filter((column) => 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>
//       <div className="rounded-md border">
//         <Table>
//           <TableHeader>
//             {table.getHeaderGroups().map((headerGroup) => (
//               <TableRow key={headerGroup.id}>
//                 {headerGroup.headers.map((header) => (
//                   <TableHead key={header.id} className="font-bold">
//                     {header.isPlaceholder ? null : (
//                       <div
//                         className={
//                           header.column.getCanSort()
//                             ? "cursor-pointer select-none flex items-center"
//                             : ""
//                         }
//                         onClick={header.column.getToggleSortingHandler()}
//                       >
//                         {flexRender(
//                           header.column.columnDef.header,
//                           header.getContext()
//                         )}
//                         {/* {[header.column.getIsSorted() ]} */}
//                       </div>
//                     )}
//                   </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 results.
//                 </TableCell>
//               </TableRow>
//             )}
//           </TableBody>
//         </Table>
//       </div>
//       <div className="flex items-center justify-end space-x-2 py-4">
//         <div className="flex-1 text-sm text-muted-foreground">
//           {table.getFilteredRowModel().rows.length} total rows
//         </div>
//         <div className="space-x-2">
//           <Button
//             variant="outline"
//             size="sm"
//             onClick={() => table.previousPage()}
//             disabled={!table.getCanPreviousPage()}
//           >
//             Previous
//           </Button>
//           <Button
//             variant="outline"
//             size="sm"
//             onClick={() => table.nextPage()}
//             disabled={!table.getCanNextPage()}
//           >
//             Next
//           </Button>
//         </div>
//       </div>
//     </div>
//   );
// }

"use client";
import * as React from "react";
import {
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import {
  ArrowUpDown,
  ChevronDown,
  ChevronsLeft,
  ChevronsRight,
  Loader2,
  MoreHorizontal,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useModal } from "@/context/ModalProvider";

const TablePagination = ({ table }) => {
  const rowCount = table.getRowCount();
  const pageSize = table.getState().pagination.pageSize;
  const displayAll = rowCount > 10 ? "All" : null;

  return (
    <div className="flex justify-between items-center my-2">
      <div className="flex items-center space-x-2">
        <span className="text-sm"> Items Per Page: </span>
        <select
          className="text-sm border rounded-md p-1"
          value={pageSize === rowCount ? "All" : pageSize}
          onChange={(e) => {
            const selectedValue = e.target.value;
            // Determine the new page size
            const newPageSize =
              selectedValue === "All" ? rowCount : Number(selectedValue);
            table.setPageSize(newPageSize);
          }}
        >
          {/* Standard Page Size Options */}
          {[5,10, 20, 30, 50].map((size) => (
            <option key={size} value={size}>
              {size}
            </option>
          ))}
          {/* Conditionally Render the "All" Option */}
          {displayAll && (
            <option key="all" value="All">
              All
            </option>
          )}
        </select>
      </div>
      {/* Pagination Controls */}
      <div className="pagination-controls">
        <Button
          variant="outline"
          size="sm"
          onClick={() => table.previousPage()}
          disabled={!table.getCanPreviousPage()}
        >
          <ChevronsLeft />
        </Button>
        <span className="mx-2">
          Page {table.getState().pagination.pageIndex + 1} of{" "}
          {table.getPageCount()}
        </span>
        <Button
          variant="outline"
          size="sm"
          onClick={() => table.nextPage()}
          disabled={!table.getCanNextPage()}
        >
          <ChevronsRight />
        </Button>
      </div>
    </div>
  );
};

export function DataTable({
  fetchData,
  columnsConfig,
  searchFields,
  EditComponent = null,
  onDelete,
  filters,
  onView,
  tag,
}) {
  const queryClient = useQueryClient();
  const { openModal } = useModal();

  const [sorting, setSorting] = React.useState([]);
  const [columnFilters, setColumnFilters] = React.useState([]);
  const [columnVisibility, setColumnVisibility] = React.useState({});
  const [rowSelection, setRowSelection] = React.useState({});
  const [pagination, setPagination] = React.useState({
    pageIndex: 0,
    pageSize: 10,
  });

  // Fetch Data Using React Query
  const { data: tableData, isLoading } = useQuery({
    queryKey: [
      tag,
      pagination.pageIndex,
      pagination.pageSize,
      sorting,
      filters,
    ],
    queryFn: () =>
      fetchData(pagination.pageIndex, pagination.pageSize, sorting, filters),
    staleTime: 300000, // 5 minutes
  });

  const handleDeleteClick = async (id) => {
    if (window.confirm("Are you sure you want to delete this item?")) {
      try {
        await onDelete(id);
        queryClient.invalidateQueries([tag]);
      } catch (error) {
        console.error("Delete error:", error);
      }
    }
  };
  const handleEditClick = (row) => {
    openModal(
      <EditComponent
        key={row.original.id}
        type="edit"
        editData={row.original}
      />
    );
  };

  // Define actions column
  const actionsColumn = {
    id: "actions",
    enableHiding: false,
    cell: ({ row }) => {
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">Open menu</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>Actions</DropdownMenuLabel>
            {onView && (
              <DropdownMenuItem onClick={() => onView(row.original)}>
                View Details
              </DropdownMenuItem>
            )}
            {EditComponent && (
              <DropdownMenuItem onClick={() => handleEditClick(row)}>
                Edit
              </DropdownMenuItem>
            )}
            {onDelete && (
              <DropdownMenuItem
                onClick={() => handleDeleteClick(row.original.id)}
                className="text-red-600"
              >
                Delete
              </DropdownMenuItem>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  };

  // Combine user columns with actions column
  const columns = [...columnsConfig, actionsColumn];

  const table = useReactTable({
    data: tableData?.rows || [],
    columns,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onPaginationChange: setPagination,
    onRowSelectionChange: setRowSelection,
    state: {
      pagination,
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-48">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="w-full">
      <div className="flex items-center py-4">
        {searchFields && (
          <Input
            placeholder={`Search ${searchFields}...`}
            value={table.getColumn(searchFields)?.getFilterValue() ?? ""}
            onChange={(event) =>
              table.getColumn(searchFields)?.setFilterValue(event.target.value)
            }
            className="max-w-sm"
          />
        )}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" className="ml-auto">
              Columns <ChevronDown />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {table
              .getAllColumns()
              .filter((column) => 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>
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead key={header.id} className="font-bold">
                    {header.isPlaceholder ? null : (
                      <div
                        className={
                          header.column.getCanSort()
                            ? "cursor-pointer select-none flex items-center"
                            : ""
                        }
                        onClick={header.column.getToggleSortingHandler()}
                      >
                        {flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                        {/* {[header.column.getIsSorted() ]} */}
                      </div>
                    )}
                  </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 results.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      <TablePagination table={table} showPagination={true} />
    </div>
  );
}
