/* eslint-disable react/no-danger */
/* 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 'gatsby-core-theme/src/hooks/modal/modalContext';
import { setCookie } from '~helpers/cookies';
import styles from './modal.module.scss';

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

  // 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 === event.target) {
        close();
      }

      // replace with this code if you want the modal to close even on click to scroll or
      // anywhere outside the modal
      // 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]);

  // eslint-disable-next-line no-shadow
  function deleteCookie(cookieName) {
    document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
  }

  const handleAcceptCookies = () => {
    setCookie(cookieName, true, 365, '/');
    setCk(true);
    deleteCookie('CookieDeclined');
    close();
  };

  return (
    <div
      className={`${styles?.modalInner || ''} ${children ? styles?.modalContainer || '' : ''}`}
      ref={modal}
    >
      {showModal && (
        <>
          <div className={styles?.modalOverlay || ''} onClick={close} />
          {modalContent && (
            <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>
          )}
          {!modalContent && (
            <div className={styles?.modalChildContainer || ''}>
              {React.cloneElement(children, {
                acceptCookies: handleAcceptCookies,
                closeModal: close,
              })}
            </div>
          )}
        </>
      )}
    </div>
  );
};

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

export default ModalContent;
