import {
  Dispatch,
  PropsWithChildren,
  createContext,
  useContext,
  useReducer,
} from 'react';

import {
  type ComparisionSurvey,
  type Nullable,
} from 'src/types/peopleExperience';

type ResultsFiltersState = {
  comparisionSurvey: Nullable<ComparisionSurvey>;
};

type ResulstFiltersContexType = {
  state: ResultsFiltersState;
  setState: Dispatch<Partial<ResultsFiltersState>>;
};

const ResultsFiltersContext = createContext<ResulstFiltersContexType | null>(
  null,
);

const reducer = (
  state: ResultsFiltersState,
  payload: Partial<ResultsFiltersState>,
) => {
  return { ...state, ...payload };
};

const initialState: ResultsFiltersState = { comparisionSurvey: null };

export const ResultsFiltersProvider = ({ children }: PropsWithChildren) => {
  const [state, setState] = useReducer(reducer, initialState);
  const contextValue = { state, setState };
  return (
    <ResultsFiltersContext.Provider value={contextValue}>
      {children}
    </ResultsFiltersContext.Provider>
  );
};

const useResultsFilters = () => {
  const context = useContext(ResultsFiltersContext);
  if (context === undefined) {
    throw new Error(
      'useResultsFilters must be used within a ResultsFiltersProvider',
    );
  }
  return context;
};
export default useResultsFilters;
