import { Fragment, useEffect } from 'react';
import {
  StyledModal,
  StyledOverlay,
  CloseIcon,
} from '../ui/Modal';

interface IProps {
  isOpen: boolean;
  onEscPressed: (e: any) => any;
  onBackgroundClick: (e: any) => any;
  onCloseClick: (e: any) => any;
  width?: string;
  height?: string;
  children: any;
}

export default function Modal(props: IProps) {
  useEffect(() => {
    if (props.isOpen) {
      document.addEventListener("keydown", handleKeyDown, false);
    } else {
      document.removeEventListener("keydown", handleKeyDown, false);
    }

    return () => {
      document.removeEventListener("keydown", handleKeyDown, false);
    };
  }, [props.isOpen]);

  function handleKeyDown(event: any): any {
    if (event.keyCode === 27) {
      props.onEscPressed(event);
    }
  }
  return (
    <Fragment>
    {
      props.isOpen &&
      <StyledOverlay className="modal" onMouseDown={props.onBackgroundClick} onKeyDown={handleKeyDown}>
        <StyledModal width={props.width} height={props.height} onClick={(e) => e.stopPropagation()}>
          <CloseIcon onClick={props.onCloseClick} />
          {props.children}
        </StyledModal>
      </StyledOverlay>
    }
    </Fragment>
  );
}
