import TanstackTable from "@/components/tanstack-table";
import {
  ColumnDef,
  ColumnFiltersState,
  OnChangeFn,
  PaginationState,
  RowSelectionState,
  SortingState,
  VisibilityState,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  useReactTable,
} from "@tanstack/react-table";
import React, { useCallback, useEffect } from "react";

export type TanstackTableT<T = any> = {
  setPagination: React.Dispatch<React.SetStateAction<PaginationState>>;
  pagination: PaginationState;
  columns: ColumnDef<T>[];
  data: T[];
  setData: React.Dispatch<React.SetStateAction<T[]>>;
  rowSelection: RowSelectionState;
  setRowSelection: React.Dispatch<React.SetStateAction<RowSelectionState>>;
  columnVisibility: VisibilityState;
  setColumnVisibility: React.Dispatch<React.SetStateAction<VisibilityState>>;
  onRowClick?: (data: T) => void;
  rowCount: number;
  sorting?: SortingState;
  setSorting?: React.Dispatch<React.SetStateAction<SortingState>>;
  columnFilters?: ColumnFiltersState | undefined;
  onColumnFiltersChange?: OnChangeFn<ColumnFiltersState> | undefined;
};

function fallback() {}

const useTable = ({
  columnVisibility,
  columns,
  data,
  pagination,
  rowSelection,
  setColumnVisibility,
  setData,
  setPagination,
  setRowSelection,
  onRowClick,
  setSorting,
  sorting,
  rowCount,
  columnFilters,
  onColumnFiltersChange,
}: TanstackTableT) => {
  const table = useReactTable({
    data,
    columns,
    rowCount: rowCount,
    manualPagination: true,
    manualSorting: true,
    state: {
      rowSelection,
      pagination,
      columnVisibility,
      sorting,
      columnFilters,
    },
    enableRowSelection: true, //enable row selection for all rows
    // enableRowSelection: (row) => row.original.age > 18, // or enable row selection conditionally per row
    onRowSelectionChange: setRowSelection,
    onColumnFiltersChange,
    getRowId: (originalRow, index, parent) => originalRow.id,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    onPaginationChange: setPagination,
    onColumnVisibilityChange: setColumnVisibility,
    onSortingChange: setSorting,
    // debugTable: true,
  });

  const Table = useCallback(() => {
    return <TanstackTable table={table} onRowClick={onRowClick} />;
  }, [data, rowSelection, columnFilters]);

  return {
    Table,
    table,
  };
};

export default useTable;
