import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { canUseDOM } from '../../helpers/dom';

const createContainer = (zIndex: number): HTMLDivElement => {
  const container = document.createElement('div');
  container.setAttribute('class', 'portal');
  container.setAttribute('style', `z-index: ${zIndex};`);
  return container;
};

type Props = {
  zIndex?: number;
  children: React.ReactNode;
};

const Portal : React.FunctionComponent<Props> = ({
  zIndex = 0,
  children = '',
}) => {
  const [container, setContainer] = useState(canUseDOM() ? createContainer(zIndex) : undefined);

  useEffect(() => {
    if (container) {
      document.body.appendChild(container);
    } else {
      const newContainer = createContainer(zIndex);
      setContainer(newContainer);
    }

    return () => {
      if (container) {
        document.body.removeChild(container);
      }
    };
  }, [])

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

export default Portal;
