/* eslint-disable react/forbid-prop-types */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-unused-expressions */
/* eslint-disable react/button-has-type */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable react/no-danger */
import React, { useRef, useEffect, useState, useContext } from 'react';
import PropTypes from 'prop-types';
import { MdClose } from '@react-icons/all-files/md/MdClose';
import { translate } from 'gatsby-core-theme/src/helpers/getters';
import { Context } from 'gatsby-core-theme/src/context/MainProvider';
import { isMobileDevice } from 'gatsby-core-theme/src/helpers/device-detect';
import Link from 'gatsby-core-theme/src/hooks/link';
import PopupCard from '../../atoms/cards/popup-card';
import { setIdleTimeout } from '../../../helpers/popup';
import months from '../../../constants/months';

import styles from './popup.module.scss';

const Popup = ({
  module,
  isStorybook = false,
  toggle = false,
  icon = null,
  numberOfItems = 4,
  link = false,
  template,
}) => {
  const modal = useRef(null);
  const [showModal, setShowModal] = useState(false);
  const [isIdle, setIsIdle] = useState(false);
  const { items } = module.items[0];
  const shownItems = items?.slice(0, numberOfItems) || [];
  const { style } = module;
  const tracker = isMobileDevice() ? 'mobPopup' : 'Popup';
  const { translations } = useContext(Context) || {};
  const date = new Date();
  const month = months[date.getMonth()];
  const title = translate(translations, 'popup_title', 'Claim These Exclusive Bonuses').replace(
    'month',
    month
  );

  const toggleTitle = translate(
    translations,
    'popup_toggle_title',
    'Claim These Exclusive Bonuses'
  ).replace('month', month);

  const handelActive = (status) => {
    setShowModal(status);
  };

  const idleTimeout = () => {
    setIsIdle(true);
  };

  const displayModal = () => {
    const popupExists = sessionStorage.getItem('popstate');
    if (!popupExists) {
      setShowModal(true);
      sessionStorage.setItem('popstate', true);
    }
  };

  const handleEsc = (event) => {
    if (event.keyCode === 27) {
      setShowModal(false);
    }
  };

  const handleOutsideClick = (event) => {
    if (modal.current && modal?.current === event.target) {
      setShowModal(false);
    }
  };

  useEffect(() => {
    if (isIdle) {
      window.addEventListener('scroll', displayModal);
    }
  }, [isIdle]);

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

  // Close on esc
  // Close on outside click
  // Show Popup on Idle and on window leave
  useEffect(() => {
    const time = process.env.EXPIRE_SECONDS_POPUP;
    const expireSeconds = typeof time !== 'undefined' ? time : 20;

    isStorybook && setShowModal(true);
    window.addEventListener('keydown', handleEsc);
    window.addEventListener('mousedown', handleOutsideClick);
    window.addEventListener('load', setIdleTimeout(expireSeconds, idleTimeout));
    document.addEventListener('mouseleave', displayModal);

    // Clean up event listeners after popup is closed
    return () => {
      window.removeEventListener('keydown', handleEsc);
      window.removeEventListener('mousedown', handleOutsideClick);
      window.removeEventListener('load', setIdleTimeout);
      document.removeEventListener('mouseleave', displayModal);
    };
  }, []);

  return (
    <div
      className={`${styles?.popup || ''} ${
        toggle ? styles?.toggleButton || '' : styles?.defaultPopup || ''
      } ${style ? styles[style] || '' : ''}`}
    >
      {showModal && (
        <div onClick={() => handelActive(false)} className={styles?.modalOverlay || ''} />
      )}
      <div className={`${styles?.modalInner || ''} `} ref={modal}>
        <div className={styles?.itemsContent || ''}>
          <div className={styles?.popupCenter || ''}>
            <div className={styles?.modalContent || ''}>
              <div className={styles?.modalTitle || ''}>
                <p>{title}</p>
                <button
                  className={`${styles?.closeIcon || ''} popup-gtm btn-cta`}
                  onClick={() => handelActive(false)}
                >
                  <MdClose title="Close Icon" />
                </button>
              </div>
              {shownItems?.map((item, index) => (
                // eslint-disable-next-line react/no-array-index-key
                <PopupCard key={index} item={item} tracker={tracker} template={template} />
              ))}
            </div>
            {toggle && !link && (
              <div
                className={styles?.toggleButtonPopup || ''}
                onClick={() => {
                  handelActive(!showModal);
                }}
              >
                {icon}
                <p>{toggleTitle}</p>
              </div>
            )}
            {toggle && link && (
              <Link className={styles?.toggleButtonPopup || ''} to={link}>
                {icon}
                <p>{toggleTitle}</p>
              </Link>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

Popup.propTypes = {
  module: PropTypes.shape({
    items: PropTypes.arrayOf(PropTypes.object),
    style: PropTypes.string,
  }).isRequired,
  isStorybook: PropTypes.bool,
  toggle: PropTypes.bool,
  icon: PropTypes.elementType,
  numberOfItems: PropTypes.number,
  link: PropTypes.bool || PropTypes.string,
  template: PropTypes.string,
};

export default Popup;
