import React, { PropsWithChildren, useEffect, useRef, useState } from 'react';
import GlobalModalServices from '.';
import type { GlobalModalServicesModalMethods } from './type';

const GlobalModalContext = React.createContext(
  {} as {
    dispatch: GlobalModalServicesModalMethods;
  },
);

export const useGlobalModalServices = () =>
  React.useContext(GlobalModalContext);

/** 全局弹窗服务提供者 */
const GlobalModalServicesProvider: React.FC<PropsWithChildren> = (props) => {
  const [dispatch, setDispatch] = useState<GlobalModalServicesModalMethods>();
  const ref = useRef<GlobalModalServicesModalMethods>(null);

  useEffect(() => {
    if (ref.current && !dispatch) {
      setDispatch(ref.current);
    }
  }, [ref.current]);

  return (
    <GlobalModalContext.Provider
      value={{
        dispatch: dispatch!,
      }}
    >
      <GlobalModalServices ref={ref} />
      {props.children}
    </GlobalModalContext.Provider>
  );
};

export default GlobalModalServicesProvider;
