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

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

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

export const DataTableProvider = ({
  initialGlobalFilter = "",
  children,
}: PropsWithChildren<{
  initialGlobalFilter?: string;
}>) => {
  const [pagination, setPagination] = usePaginationParams();
  const [globalFilter, setGlobalFilter] = useState<string>(initialGlobalFilter);
  const [sorting, setSorting] = useState<SortingState>([]);

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

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