import type { ReactNode } from 'react'

import React, {
  useRef,
} from 'react'
import ReactDOM from 'react-dom'

import {
  ModalContainer,
  ModalWindow,
  ModalCloseButton,
} from './styled'

type Props = {
  children: ReactNode,
  close: () => void,
  isOpen: boolean,
}

export const Modal = ({
  children,
  close,
  isOpen,
}: Props) => {
  const modalRoot = useRef(document.getElementById('modal-root'))

  return isOpen
    ? ReactDOM.createPortal(
      <ModalContainer>
        <ModalWindow>
          <ModalCloseButton onClick={close} />
          {children}
        </ModalWindow>
      </ModalContainer>,
      modalRoot.current as Element,
    )
    : null
}
