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

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

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

/** 全局弹窗服务提供者 */
const GlobalModalServicesProvider: React.FC<PropsWithChildren> = (props) => {
  const [dispatch, setDispatch] = useState<GlobalModalPrideAction>();
  const ref = useRef<GlobalModalPrideAction>(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;
