import type { ReactNode } from 'react'
import { useMemo } from 'react'
import ReactDOM from 'react-dom'

import { OutsideClick } from 'features/OutsideClick'
import { Close } from 'features/Icons/Close'

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

const defaultCloseHandler = () => {}

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

export const Modal = ({
  children,
  className,
  close = defaultCloseHandler,
  isOpen,
  withCloseButton = true,
}: Props) => {
  const modalRoot = useMemo(
    () => document.getElementById('modal-root'),
    [],
  )

  return (isOpen && modalRoot)
    ? ReactDOM.createPortal(
      <ModalContainer className={className}>
        <OutsideClick onClick={close}>
          <ModalWindow>
            {withCloseButton && (
              <ModalCloseButton onClick={close}>
                <Close />
              </ModalCloseButton>
            )}
            {children}
          </ModalWindow>
        </OutsideClick>
      </ModalContainer>,
      modalRoot,
    )
    : null
}
