import React, { useState, useEffect } from "react"
import ReactDOM from "react-dom"

import { resovelElement } from "@utils/dom"
import { PortalProps } from "@components/Portal/interface"

/**
 * 传送门组件将其子节点渲染到当前 DOM 结构之外的新 "子类树" 当中。
 *
 * ### 引用方法
 * ```tsx
 * import { Portal } from "@atomintl/exchange-ui"
 * ```
 * */
const Portal: React.FC<PortalProps> = props => {
  const { children, container, disablePortal = false } = props
  const [mountNode, setMountNode] = useState<HTMLElement | null>(null)

  useEffect(() => {
    if (!disablePortal) {
      setMountNode(container ? resovelElement(container) : document.body)
    }
  }, [container, disablePortal])

  return mountNode ? ReactDOM.createPortal(children, mountNode) : mountNode
}

export default Portal
