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

import { OutsideClick } from 'features/OutsideClick'
import { Close } from '../../libs/objects/Close'

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

const defaultCloseHandler = () => {}

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

export const Modal = ({
  children,
  className,
  close = defaultCloseHandler,
  closeSize,
  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 size={closeSize || 8} />
              </ModalCloseButton>
            )}
            {children}
          </ModalWindow>
        </OutsideClick>
      </ModalContainer>,
      modalRoot,
    )
    : null
}
