import React, { RefObject, useContext, useEffect, useRef } from 'react';

type PopoverContextProps = { children: React.ReactNode };

type PopoverContextModel = RefObject<{ [contextId: string]: () => void }>;
const PopoverContext = React.createContext<PopoverContextModel>({ current: {} });
PopoverContext.displayName = 'SilkePopoverContext';

export function usePopoverRequestClose(popoverContextId: string): () => void {
  const context = useContext(PopoverContext);

  return () => context.current?.[popoverContextId]?.();
}

export function usePopoverContext(id?: string, hide?: boolean, onRequestClose?: () => void) {
  const context = useContext(PopoverContext);
  useEffect(() => {
    const { current } = context;
    if (current && id && !hide && onRequestClose) {
      if (current[id]) current[id]();
      current[id] = onRequestClose;

      return () => {
        if (current[id] === onRequestClose) delete current[id];
      };
    }
  }, [id, hide, onRequestClose, context]);
}

export default function SilkePopoverProvider({ children }: PopoverContextProps) {
  const contextRef = useRef<PopoverContextModel['current']>({});
  return <PopoverContext.Provider value={contextRef}>{children}</PopoverContext.Provider>;
}
