import { FC, useEffect, useState } from 'react'
import { createPortal } from 'react-dom'

import { ChildrenProp } from '../core'
import { PortalProps } from './portal.types'

/** Provided children are portaled to document.body or custom container. */
export const Portal: FC<PortalProps & ChildrenProp> = props => {
  const { children, containerRef, disablePortal } = props
  const [mountNode, setMountNode] = useState<HTMLElement>()

  useEffect(() => {
    if (!disablePortal) {
      setMountNode(containerRef?.current ?? document.body)
    }
  }, [disablePortal])

  if (disablePortal) return <>{children}</>

  return mountNode ? createPortal(children, mountNode) : <>{mountNode}</>
}

Portal.displayName = 'Portal'

export default Portal
