'use client';
import * as React from "react"
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Checkbox } from "@/components/ui/checkbox"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, PaginationState, useReactTable } from '@tanstack/react-table';




interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  totalItems: number;
  pageSizeOptions?: number[];
  onDelete: (ids: string[]) => void; // Callback for deleting selected rows
  onExport?: (ids: string[]) => void;
  otherAction?: (ids: string[]) => void;
  onSearch: (query: string) => void;
  currentPage: number;
  pageSize: number;
  disableMultiSelect?: boolean;
  otherActionBtnLabel?: string,
  onPaginationChange: (pagination: PaginationState) => void;
}



// export function DataTable<TData extends DataWithId, TValue>({
//   columns,
//   data,
//   totalItems,
//   pageSizeOptions = [10, 20, 30, 40, 50],
//   onDelete,
//   onSearch,
//   currentPage,
//   disableMultiSelect,
//   pageSize,
//   onExport,
//   otherActionBtnLabel,
//   otherAction,
//   onPaginationChange,
// }: DataTableProps<TData, TValue>) {
export const DataTable = React.forwardRef(
  (
    {
      columns,
      data,
      totalItems,
      onDelete,
      disableMultiSelect,
      setDisableMultipleSelect,
      pageSize,
      onExport,
      otherAction,
      setSelectedIds,
    }: any,
    ref
  ) => {

    // console.log(data, "-----------------data", columns)
    const pageCount = Math.ceil(totalItems / pageSize);





    const table = useReactTable({
      data,
      columns,
      pageCount,
      getCoreRowModel: getCoreRowModel(),
      manualPagination: true,
      manualFiltering: true,
      enableRowSelection: true,
    });


    const handleBulkDelete = () => {
      const selectedRowIds = table.getSelectedRowModel().rows.map((row: any) => row.original._id);
      onDelete(selectedRowIds);
      // table.resetRowSelection();
    };


    const getSelectedRowsId = () => {
      const selectedRowIds = table.getSelectedRowModel().rows.map((row: any) => row.original._id);
      setSelectedIds(selectedRowIds);
    };

    const handleResetRowSelection = () => {
      table.resetRowSelection();
    }
    const handleBulkExport = () => {
      // Collect row IDs instead of row indices
      const selectedRowIds = table.getSelectedRowModel().rows.map((row: any) => row.original._id); 
      onExport(selectedRowIds)
      const handleBulkAction = () => {
  
        const selectedRowIds = table.getSelectedRowModel().rows.map((row: any) => row.original._id);
        otherAction && otherAction(selectedRowIds); 
      };; // Send the selected row IDs to the parent for deletion
    };


    React.useImperativeHandle(ref, () => ({
      getSelectedRowsId,
      handleBulkDelete,
      handleResetRowSelection,
      handleBulkExport
    }));

    const handleMultiSelect = (type: string, row: any) => {
      if (type === "ALL") {
        table.toggleAllRowsSelected();
        setTimeout(() => {
          const selectedRowsCount = table.getSelectedRowModel().rows.length;
          setDisableMultipleSelect(selectedRowsCount === 0);
        }, 0);
      } else {
        row.toggleSelected();
        setTimeout(() => {
          const selectedRowsCount = table.getSelectedRowModel().rows.length;
          setDisableMultipleSelect(selectedRowsCount === 0);
        }, 0);
      }
    };

    return (
      <>
        <div className="space-y-4">
          <ScrollArea className="h-100 rounded-md border border-common md:h-100">
            <Table className="relative">
              {/* table header */}
              <TableHeader>
                {table.getHeaderGroups().map((headerGroup) => (
                  <TableRow key={headerGroup.id}>
                    <TableHead className="whitespace-nowrap">
                      {!disableMultiSelect && <Checkbox
                        checked={table.getIsAllRowsSelected()}
                        onCheckedChange={() => handleMultiSelect("ALL", headerGroup)}
                        aria-label="Select row"
                      />}
                    </TableHead>
                    {headerGroup.headers.map((header) => (
                      <TableHead key={header.id} className="whitespace-nowrap">
                        {header.isPlaceholder
                          ? null
                          : flexRender(header.column.columnDef.header, header.getContext())}
                      </TableHead>
                    ))}
                  </TableRow>
                ))}
              </TableHeader>

              {/* table body */}
              <TableBody>
                {table.getRowModel().rows?.length ? (
                  table.getRowModel().rows.map((row) => (
                    <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
                      <TableCell className="whitespace-nowrap">
                        {!disableMultiSelect && <Checkbox
                          checked={row.getIsSelected()}
                          onCheckedChange={() => handleMultiSelect("SINGLE", row)}
                          aria-label="Select row"
                        />}
                      </TableCell>
                      {row.getVisibleCells().map((cell) => (
                        <TableCell key={cell.id} className="whitespace-nowrap">
                          {flexRender(cell.column.columnDef.cell, cell.getContext())}
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={columns.length + 1} className="h-24 text-center">
                      No results.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
            <ScrollBar orientation="horizontal" />
          </ScrollArea>
        </div>
      </>
    );
  }
)
DataTable.displayName = 'DataTable';