import { useEffect, useState } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

function createPortalNode(nodeId) {
  const node = document.createElement('div')

  node.id = nodeId

  // we're mimicking React Native's Modal component, except for using an `absolute` position
  // this way the backdrop stays in place when scrolling the window - that's why we need to
  // position it at the scroll position when rendering
  node.style.cssText = `
  position: absolute; 
  top: ${window.scrollY}px;
  left: ${window.scrollX}px; 
  right: 0; 
  bottom: 0; 
  z-index: 100000; 
  pointer-events: none;
  `

  document.body.appendChild(node)

  return node
}

function removePortalNode(nodeId) {
  const node = document.getElementById(nodeId)

  node.parentElement.removeChild(node)
}

/**
 * The Web version of Backdrop utilizes React Portal for overlaying page content, so it is
 * dependent on ReactDOM. Tooltip's closing is handled by the onBlur callback of the control.
 */
export function Backdrop({ children }) {
  const [portalNode, setPortalNode] = useState()

  useEffect(() => {
    const nodeId = `tooltip-backdrop-${Date.now()}`

    const node = createPortalNode(nodeId)

    setPortalNode(node)

    return () => {
      removePortalNode(nodeId)
    }
  }, [])

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

Backdrop.propTypes = {
  children: PropTypes.node
}
