import React, {
  createContext,
  useContext,
  useReducer,
  ReactNode,
  useMemo,
} from "react";
import { ModalState, ModalConfig } from "@/types";

interface ModalContextType {
  modalState: ModalState;
  openModal: (
    type: ModalState["type"],
    title: string,
    data?: any,
    config?: ModalConfig
  ) => void;
  closeModal: () => void;
}

type ModalAction =
  | {
      type: "OPEN_MODAL";
      payload: {
        modalType: ModalState["type"];
        title: string;
        data?: any;
        config?: ModalConfig;
      };
    }
  | { type: "CLOSE_MODAL" };

const initialState: ModalState = {
  isOpen: false,
  type: null,
  title: "",
  data: undefined,
  config: undefined,
};

function modalReducer(state: ModalState, action: ModalAction): ModalState {
  switch (action.type) {
    case "OPEN_MODAL":
      return {
        isOpen: true,
        type: action.payload.modalType,
        title: action.payload.title,
        data: action.payload.data,
        config: action.payload.config,
      };
    case "CLOSE_MODAL":
      return {
        ...initialState,
      };
    default:
      return state;
  }
}

const ModalContext = createContext<ModalContextType | undefined>(undefined);

export function ModalProvider({ children }: { children: ReactNode }) {
  const [modalState, dispatch] = useReducer(modalReducer, initialState);

  const actions = useMemo(
    () => ({
      openModal: (
        type: ModalState["type"],
        title: string,
        data?: any,
        config?: ModalConfig
      ) => {
        dispatch({
          type: "OPEN_MODAL",
          payload: { modalType: type, title, data, config },
        });
      },
      closeModal: () => {
        dispatch({ type: "CLOSE_MODAL" });
      },
    }),
    []
  );

  return (
    <ModalContext.Provider value={{ modalState, ...actions }}>
      {children}
    </ModalContext.Provider>
  );
}

export function useModal() {
  const context = useContext(ModalContext);
  if (context === undefined) {
    throw new Error("useModal must be used within a ModalProvider");
  }
  return context;
}
