import type { Dispatch, PropsWithChildren, SetStateAction } from "react";
import { createContext, useContext, useState } from "react";
import invariant from "tiny-invariant";

import type { EvaluatorSort } from "@phoenix/pages/evaluators/__generated__/GlobalEvaluatorsTableEvaluatorsQuery.graphql";

export type EvaluatorsFilterContext = {
  filter: string;
  setFilter: Dispatch<SetStateAction<string>>;
  sort: EvaluatorSort | null | undefined;
  setSort: Dispatch<SetStateAction<EvaluatorSort | null | undefined>>;
};

export const evaluatorsFilterContext =
  createContext<EvaluatorsFilterContext | null>(null);

export const EvaluatorsFilterProvider = ({ children }: PropsWithChildren) => {
  const [filter, setFilter] = useState("");
  const [sort, setSort] = useState<EvaluatorSort | null | undefined>(undefined);
  return (
    <evaluatorsFilterContext.Provider
      value={{
        filter,
        setFilter,
        sort,
        setSort,
      }}
    >
      {children}
    </evaluatorsFilterContext.Provider>
  );
};

export const useEvaluatorsFilterContext = () => {
  const context = useContext(evaluatorsFilterContext);
  invariant(
    context,
    "useEvaluatorsFilterContext must be used within EvaluatorsFilterProvider"
  );
  return context;
};
