import React, { useEffect } from 'react'

import './ErrorPopover.scss'

const ErrorPopover = ({ children, className = '', content, onClose, open, scrollThreshold = 50 }) => {
  useEffect(() => {
    if (!onClose || !open) {
      return
    }

    const { scrollLeft, scrollTop } = document.body

    const handleScroll = () => {
      if (
        Math.abs(scrollTop - document.body.scrollTop) > scrollThreshold ||
        Math.abs(scrollLeft - document.body.scrollLeft) > scrollThreshold
      ) {
        onClose()
      }
    }

    document.addEventListener('mousedown', onClose)
    document.addEventListener('scroll', handleScroll)

    return () => {
      document.removeEventListener('mousedown', onClose)
      document.removeEventListener('scroll', handleScroll)
    }
  }, [onClose, open, scrollThreshold])

  return (
    <div className={`${className} popover-offset-parent`}>
      {children}
      {open && (
        <div className="popover-content" onMouseDown={(event) => event.stopPropagation()} role="alert">
          {content}
        </div>
      )}
    </div>
  )
}

export default ErrorPopover
