/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */

import React, { useContext, useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import { ModalContext } from './modalContext';
import styles from './modal.module.scss';

const ModalContent = ({ closeIcon }) => {
  const { showModal, setShowModal, modalContent, setModalContent } = useContext(ModalContext);
  const modal = useRef(null);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const close = () => {
    setShowModal(false);
    setModalContent('');
  };

  useEffect(() => {
    if (showModal) {
      modal.current.classList.toggle(styles.activeModal);
    } else {
      modal.current.classList.remove(styles.activeModal);
    }
  }, [showModal]);

  // Close on esc
  useEffect(() => {
    const handleEsc = (event) => {
      if (event.keyCode === 27) {
        close();
      }
    };
    if (typeof window !== 'undefined') window.addEventListener('keydown', handleEsc);
    return () => {
      if (typeof window !== 'undefined') window.removeEventListener('keydown', handleEsc);
    };
  }, [close]);

  // Close on outside click
  useEffect(() => {
    const handleOutsideClick = (event) => {
      if (
        modal.current &&
        !modal.current.contains(event.target) &&
        !modal.current.previousElementSibling.contains(event.target)
      ) {
        close();
      }
    };
    if (typeof window !== 'undefined') window.addEventListener('mousedown', handleOutsideClick);
    return () => {
      if (typeof window !== 'undefined')
        window.removeEventListener('mousedown', handleOutsideClick);
    };
  }, [close]);

  return (
    <div className={styles.modalInner} ref={modal}>
      <div className={styles.modalOverlay} onClick={close} />
      <div className={styles.modalContent}>
        {closeIcon && (
          <button
            className={`${styles.closeIcon} modal-gtm btn-cta`}
            aria-label="Close Icon"
            type="button"
            onClick={close}
          >
            {closeIcon}
          </button>
        )}
        <div dangerouslySetInnerHTML={{ __html: modalContent }} />
      </div>
    </div>
  );
};

ModalContent.propTypes = {
  closeIcon: PropTypes.oneOfType([PropTypes.element, PropTypes.any]),
};

export default ModalContent;
