import { useCallback, useMemo, useReducer } from "react";

import ConfirmContext from "./ConfirmContext";
import {
  HIDE_CONFIRM,
  initialState,
  reducer,
  SHOW_CONFIRM,
} from "./ConfirmReducer";

export default function ConfirmContextProvider({
  children,
}: React.PropsWithChildren) {
  const [state, dispatch] = useReducer(reducer, initialState);

  const showConfirm = useCallback((text: string) => {
    dispatch({
      payload: {
        text,
      },
      type: SHOW_CONFIRM,
    });
  }, []);

  const closeConfirm = useCallback(() => {
    dispatch({
      type: HIDE_CONFIRM,
    });
  }, []);

  const actions = useMemo(
    () => ({
      closeConfirm,
      showConfirm,
    }),
    [showConfirm, closeConfirm],
  );

  return (
    <ConfirmContext.Provider value={[state, actions]}>
      {children}
    </ConfirmContext.Provider>
  );
}
