import React, { useMemo, useLayoutEffect } from 'react';
import ReactDOM from 'react-dom';

function Portal({ className, content, visible, focusRender, children, getContainer, ...props }) {
  const ele = useMemo(() => {
    const div = document.createElement('div');
    div.className = className;
    return div;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const renderContent = useMemo(() => {
    if (visible || focusRender) {
      return content || children;
    } else {
      return null;
    }
  }, [visible, content, children, focusRender]);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const container = useMemo(() => getContainer(), [getContainer()]);
  useLayoutEffect(() => {
    container && container.appendChild(ele);
    return () => ele.remove();
  }, [ele, container]);

  useLayoutEffect(() => {
    if (focusRender) {
      ele.style.display = visible ? 'block' : 'none';
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, focusRender]);

  return ReactDOM.createPortal(renderContent, ele);
}
Portal.defaultProps = {
  className: '',
  focusRender: false,
  visible: true,
  getContainer: () => document.body
};

export default React.memo(Portal);
