import React, { FC, ReactNode, useEffect, useRef } from 'react';
import ReactModal from 'react-modal';

import css from './index.module.css';
import classnames from 'classnames';
import { MilaGridColumn, MilaGridVoid } from '../../index';
import CloseSVG from '../../assets/icons/icon_close.svg';

export interface ModalRedesignProps {
  isOpen?: boolean;
  error?: string;
  children?: ReactNode;
  actions?: ReactNode;
  title?: string;
  withAnimation: boolean;
  onRequestClose: () => void;
}

const ModalRedesign: FC<ModalRedesignProps> = ({
  isOpen,
  children,
  onRequestClose,
  withAnimation = false,
  ...rest
}) => {
  const modalContent = useRef();
  const handleClickOutside = (e): void => {
    // @ts-ignore
    if (modalContent.current && !modalContent.current.contains(e.target)) {
      onRequestClose();
    }
  };
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);

    return (): void => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  });

  return (
    <ReactModal
      {...rest}
      isOpen={isOpen}
      className={classnames('mila-container', css.modal__container, {
        [css.modal__open]: isOpen && withAnimation,
        [css.modal__close]: !isOpen && withAnimation,
      })}
      overlayClassName={css.modal}
      ariaHideApp={false}
      onRequestClose={onRequestClose}
      shouldCloseOnOverlayClick={true}
    >
      <MilaGridVoid>
        <MilaGridColumn
          columns={['sm-12', 'xl-10', 'xxl-8']}
          offset={['xl-1', 'xxl-2']}
          className={css.modal__content}
          divRef={modalContent}
        >
          <div className={css.modal__iconWrapper}>
            <CloseSVG
              className={css.modal__closeIcon}
              onClick={(): void => {
                onRequestClose();
              }}
            />
          </div>
          {children}
        </MilaGridColumn>
      </MilaGridVoid>
    </ReactModal>
  );
};
export default ModalRedesign;
