import React, { FC, useEffect, useState } from 'react';
import ReactModal from 'react-modal';
import css from './index.module.css';
import IconHelpSVG from '../../assets/icons/icon_help.svg';
import CloseSVG from '../../assets/icons/icon_close.svg';

export interface ToolTipModalProps {
  title: string;
  description: string;
  iconClass?: string;
}

const ToolTipModal: FC<ToolTipModalProps> = ({
  title,
  description,
  iconClass,
}) => {
  const [modalIsOpen, setIsOpen] = React.useState(false);
  const [isDesktop, setDesktop] = useState(null);
  const [isToolTipShown, setIsToolTipOpen] = useState(null);

  const openModal = (): void => {
    setIsOpen(true);
  };

  const closeModal = (): void => {
    setIsOpen(false);
  };

  const updateMedia = (): void => {
    setDesktop(window.innerWidth > 700);
    window.innerWidth < 700 ? setIsToolTipOpen(false) : null;
  };

  useEffect(() => {
    setDesktop(window.innerWidth > 700);
  }, []);

  useEffect(() => {
    window.addEventListener('resize', updateMedia);
    return (): void => window.removeEventListener('resize', updateMedia);
  });

  const renderContent = (): JSX.Element => {
    return (
      <>
        <div className={css.tooltip__title}>
          {title}
          {!isToolTipShown && (
            <div className={css.tooltip__close} onClick={closeModal}>
              <CloseSVG className={css.tooltip__closeLogo} />
            </div>
          )}
        </div>

        <div className={css.tooltip__content}>{description}</div>
      </>
    );
  };

  return (
    <div>
      <div
        className={`${iconClass ? iconClass : css.tooltip__icon}`}
        onClick={
          isDesktop
            ? (): boolean => {
                return false;
              }
            : openModal
        }
        onMouseOver={(): void => {
          isDesktop ? setIsToolTipOpen(true) : false;
        }}
        onMouseLeave={(): void => {
          isDesktop ? setIsToolTipOpen(false) : false;
        }}
      >
        <IconHelpSVG />
      </div>

      {isToolTipShown && (
        <div className={css.tooltip__container}>{renderContent()}</div>
      )}
      <ReactModal
        isOpen={modalIsOpen}
        className={css.tooltip__modal}
        overlayClassName={css.tooltip__overlay}
        onRequestClose={closeModal}
        shouldCloseOnOverlayClick={true}
        ariaHideApp={false}
        contentLabel="Example Modal"
      >
        {renderContent()}
      </ReactModal>
    </div>
  );
};

export default ToolTipModal;
