import { h, type FunctionComponent } from 'preact'
import { useEffect } from 'preact/hooks'
import Portal from '../../shared/components/portal.tsx'
import disableScroll from '../../shared/utils/disable_scroll.ts'
import stopPropagation from '../../shared/utils/stop_propagation.ts'
import Button from './button.tsx'
import s from './modal.module.scss'

const Modal: FunctionComponent<{ onClose?: (e: ANY) => void }> = ({ children, onClose }) => {
  useEffect(() => {
    function onKeyUp(e: ANY) {
      if (e.keyCode === 27) onClose!(e)
    }

    disableScroll.disable()

    if (onClose) addEventListener('keyup', onKeyUp)

    return () => {
      disableScroll.enable()
      removeEventListener('keyup', onKeyUp)
    }
  }, [])

  return (
    <Portal>
      <div className={s.overlay} onClick={onClose}>
        <div className={s.base} onClick={stopPropagation}>
          {onClose && (
            <Button onClick={onClose} className={s.closeButton}>
              X
            </Button>
          )}
          <div className={s.content}>{children}</div>
        </div>
      </div>
    </Portal>
  )
}

export default Modal
