import { PaginationState } from "@/lib/hooks";
import { SortingState } from "@tanstack/react-table";
import {
  Dispatch,
  PropsWithChildren,
  SetStateAction,
  createContext,
  useCallback,
  useMemo,
  useState,
} from "react";
import { useSyncedPagination } from "./useSyncedPagination";

export interface IDataTableContextState {
  pagination: PaginationState;
  setPagination: (newPagination: PaginationState) => void;
  sorting: SortingState;
  setSorting: Dispatch<SetStateAction<SortingState>>;
  globalFilter: string[];
  setGlobalFilter: Dispatch<SetStateAction<string[]>>;
  resetGlobalFilter: () => void;
  isFiltered: boolean;
}

export const DataTableContext = createContext<IDataTableContextState | null>(null);

export const DataTableProvider = ({
  syncWithLocation = true,
  initialGlobalFilter = [],
  initialPageIndex,
  initialPageSize,
  children,
}: PropsWithChildren<{
  syncWithLocation?: boolean;
  initialGlobalFilter?: string[];
  initialPageIndex?: number;
  initialPageSize?: number;
}>) => {
  const [pagination, setPagination] = useSyncedPagination({
    syncWithLocation,
    initialPageIndex,
    initialPageSize,
  });
  const [globalFilter, setGlobalFilter] = useState<string[]>(initialGlobalFilter || []);
  const [sorting, setSorting] = useState<SortingState>([]);

  const isFiltered = useMemo(() => Boolean(globalFilter && globalFilter.length), [globalFilter]);
  const resetGlobalFilter = useCallback(() => setGlobalFilter([]), []);

  return (
    <DataTableContext.Provider
      value={{
        pagination,
        setPagination,
        sorting,
        setSorting,
        globalFilter,
        setGlobalFilter,
        resetGlobalFilter,
        isFiltered,
      }}
    >
      {children}
    </DataTableContext.Provider>
  );
};
