import * as React from 'react';
import { useRef, useEffect, forwardRef, useImperativeHandle } from 'react';
import ReactDOM from 'react-dom';

interface PropsType {
  didUpdate?: Function
  getContainer: Function
  children?: React.ReactNode
}

const Portal = forwardRef((props: PropsType, ref) => {
  const { didUpdate, getContainer= () => {return null}, children=null } = props;

  const containerRef: any = useRef();

  // Ref return nothing, only for wrapper check exist
  useImperativeHandle(ref, () => ({}));

  // Create container in client side with sync to avoid useEffect not get ref
  const initRef = useRef(false);
  if (!initRef.current) {
    containerRef.current = getContainer();
    initRef.current = true;
  }

  useEffect(() => {
    didUpdate?.(props);
  });

  useEffect(() => {
    return () => {
      containerRef.current?.parentNode?.removeChild(containerRef.current);
    };
  }, []);

  return containerRef.current
    ? ReactDOM.createPortal(children, containerRef.current)
    : null;
});


export default Portal;