import { PropsWithChildren, createContext, useContext, useMemo } from 'react';

/** Value of {@link ModalDialogContext} */
export interface ModalDialogContextValue {
  /** Unique id of the modal dialog */
  id: string;
}

const ModalDialogContext = createContext<ModalDialogContextValue | undefined>(undefined);

/** Provider modal dialog data */
export function ModalDialogContextProvider({ id, children }: PropsWithChildren<ModalDialogContextValue>) {
  const value: ModalDialogContextValue = useMemo(() => ({ id }), [id]);

  return <ModalDialogContext.Provider value={value}>{children}</ModalDialogContext.Provider>;
}

/** Return data for modal dialog */
export function useModalDialogContext(): ModalDialogContextValue {
  const value = useContext(ModalDialogContext);
  if (!value) {
    throw new Error('useModalDialogContext should be used only inside ModalDialogContextProvider');
  }

  return value;
}
