"use client";

import { createContext, useContext, useState, ReactNode } from "react";
import { MODAL_REGISTRY } from "./ModalRegistery";

type ModalRegistry = typeof MODAL_REGISTRY;
type ModalType = keyof ModalRegistry;

type ModalState =
  | { type: null; props?: undefined }
  | {
      [K in ModalType]: {
        type: K;
        props: React.ComponentProps<ModalRegistry[K]>;
      };
    }[ModalType];

type ModalContextType = {
  modal: ModalState;
  openModal: <T extends ModalType>(
    type: T,
    props: React.ComponentProps<ModalRegistry[T]>,
  ) => void;
  closeModal: () => void;
};

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

export const ModalProvider = ({ children }: { children: ReactNode }) => {
  const [modal, setModal] = useState<ModalState>({ type: null });

  const openModal = <T extends ModalType>(
    type: T,
    props: React.ComponentProps<ModalRegistry[T]>,
  ) => {
    setModal({ type, props } as Extract<ModalState, { type: T }>);
  };

  const closeModal = () => {
    setModal({ type: null });
  };

  return (
    <ModalContext.Provider value={{ modal, openModal, closeModal }}>
      {children}
    </ModalContext.Provider>
  );
};

export const useModal = () => {
  const ctx = useContext(ModalContext);
  if (!ctx) throw new Error("useModal must be used within ModalProvider");
  return ctx;
};
