/* eslint-disable import/no-extraneous-dependencies */
import React, { useContext, useState, useRef, useEffect } from 'react';
import PropTypes from 'prop-types';

import { Context } from 'gatsby-core-theme/src/context/MainProvider';
import { MdClose } from '@react-icons/all-files/md/MdClose';
import Link from 'gatsby-core-theme/src/hooks/link';
import { translate } from '~helpers/getters';
import CategoryContainer from './category/index';
import Button from '~atoms/button/button';
import LazyImage from '~hooks/lazy-image';
import styles from './cookie-modal.module.scss';

const CookieModal = ({
  handleAcceptCookies,
  handleDeclineCookies,
  declineButtonType = 'secondary',
  buttonSize = 'm',
  closeModal,
  cookieLink = {
    title: '',
    path: '',
  },
  logo = '../../../../../images/logo.svg',
  templateTwo = false,
  hide,
  ck,
}) => {
  const [categorySection, setCategorySection] = useState(0);
  const [anlyticsButton, setAnlyticsButton] = useState(false);
  const [marketing, setMarketingButton] = useState(false);
  const [menage, setMenage] = useState(true);
  const { translations } = useContext(Context) || {};

  const modal = useRef(null);

  const handlePreference = () => {
    if (templateTwo) {
      setMenage(!menage);
    }
  };

  const handleOutsideClick = (event) => {
    if (modal.current && modal?.current === event.target) {
      closeModal(false);
      document.body.style.overflow = 'auto';
    }
  };

  useEffect(() => {
    window.addEventListener('mousedown', handleOutsideClick);
    return () => {
      window.removeEventListener('mousedown', handleOutsideClick);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const CategoryObj = [
    {
      translateKey: 'neccesary_cookie_title',
      button: false,
      altTranslation: 'Neccesary',
      textKey: 'neccesary_cookie_text',
      defaultText:
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nibh aliquam non sit morbi neque in sodales tellus. Cursus neque sed quis tincidunt sed vestibulum rhoncus dolor elementum. Imperdiet tortor dolor sit nisi, magnis cras id ut. Id dolor, vel neque lobortis. Diam commodo vitae vulputate at ultrices id odio praesent. Nisi, sit massa orci accumsan.',
    },
    {
      translateKey: 'analytical_cookie_title',
      button: true,
      altTranslation: 'Analytical And Stadistical',
      textKey: 'analytical_cookie_text',
      defaultText:
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nibh aliquam non sit morbi neque in sodales tellus. Cursus neque sed quis tincidunt sed vestibulum rhoncus dolor elementum. Imperdiet tortor dolor sit nisi, magnis cras id ut. Id dolor, vel neque lobortis. Diam commodo vitae vulputate at ultrices id odio praesent. Nisi, sit massa orci accumsan.',
    },
    {
      translateKey: 'marketing_cookie_title',
      button: true,
      altTranslation: 'Marketing',
      textKey: 'marketing_cookie_text',
      defaultText:
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nibh aliquam non sit morbi neque in sodales tellus. Cursus neque sed quis tincidunt sed vestibulum rhoncus dolor elementum. Imperdiet tortor dolor sit nisi, magnis cras id ut. Id dolor, vel neque lobortis. Diam commodo vitae vulputate at ultrices id odio praesent. Nisi, sit massa orci accumsan.',
    },
  ];
  return (
    <div className={`${!hide ? styles.container : styles.hide}`} ref={modal}>
      <div className={`${styles?.modalContent} ${templateTwo ? styles.modalContentTwo : null}`}>
        <div className={styles?.modalCookieHeader || ''}>
          {!templateTwo ? (
            <LazyImage
              alt={`${process.env.GATSBY_SITE_NAME} logo`}
              width={150}
              height={21}
              src={logo}
            />
          ) : (
            <span>
              {translate(translations, 'privacy_preference_title', 'Privacy Preference Center')}
            </span>
          )}
          <button type="button" onClick={() => closeModal()}>
            <MdClose title="Close Icon" />
          </button>
        </div>
        <div className={styles?.modalTextHeader || ''}>
          {!templateTwo && (
            <span>
              {translate(translations, 'privacy_preference_title', 'Privacy Preference Center')}
            </span>
          )}
          <p>
            {translate(
              translations,
              'privacy_preference_text',
              'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nibh aliquam non sit morbi neque in sodales tellus. Cursus neque sed quis tincidunt sed vestibulum rhoncus dolor elementum. Imperdiet tortor dolor sit nisi, magnis cras id ut. Id dolor, vel neque lobortis. Diam commodo vitae vulputate at ultrices id odio praesent. Nisi, sit massa orci accumsan.'
            )}
            {cookieLink?.title && cookieLink?.path && (
              <Link to={cookieLink?.path} className={styles.cookieLink}>
                {cookieLink?.title}
              </Link>
            )}
          </p>
        </div>
        <div className={styles?.modalButtons || ''}>
          {!ck && (
            <Button
              onClick={() => handleAcceptCookies()}
              btnText={translate(translations, 'cookie_accept_all_button', 'Accept All Cookies')}
              isInternalLink={false}
              buttonType="primary"
              buttonSize={buttonSize}
              gtmClass="cookie-consent-gtm btn-cta"
            />
          )}
          <Button
            onClick={() => handleDeclineCookies()}
            btnText={translate(
              translations,
              'cookie_reject_nonnecessary_button',
              'I reject Non-Necessary'
            )}
            isInternalLink={false}
            buttonType={declineButtonType}
            buttonSize={buttonSize}
            gtmClass="cookie-consent-gtm btn-cta"
          />
        </div>
        <div className={`${styles?.mainBox || ''} ${menage && styles?.mainBoxStyleTwoFullHeight}`}>
          <span
            onClick={() => handlePreference()}
            aria-hidden="true"
            className={styles?.mainTitle || ''}
          >
            {translate(translations, 'menage_consent_preference', 'Manage Consent Preferences')}
            {templateTwo && (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                className={(!menage && styles.menageArrow) || ''}
              >
                <path
                  d="M16.9997 13.4101L12.7097 9.17007C12.6167 9.07634 12.5061 9.00194 12.3843 8.95117C12.2624 8.90041 12.1317 8.87427 11.9997 8.87427C11.8677 8.87427 11.737 8.90041 11.6151 8.95117C11.4933 9.00194 11.3827 9.07634 11.2897 9.17007L7.0497 13.4101C6.95598 13.503 6.88158 13.6136 6.83081 13.7355C6.78004 13.8573 6.75391 13.9881 6.75391 14.1201C6.75391 14.2521 6.78004 14.3828 6.83081 14.5046C6.88158 14.6265 6.95598 14.7371 7.0497 14.8301C7.23707 15.0163 7.49052 15.1209 7.7547 15.1209C8.01889 15.1209 8.27234 15.0163 8.4597 14.8301L11.9997 11.2901L15.5397 14.8301C15.726 15.0148 15.9774 15.119 16.2397 15.1201C16.3713 15.1208 16.5018 15.0956 16.6236 15.0458C16.7454 14.9961 16.8563 14.9227 16.9497 14.8301C17.0468 14.7404 17.1251 14.6325 17.1802 14.5124C17.2353 14.3923 17.2661 14.2625 17.2708 14.1305C17.2754 13.9985 17.2539 13.8668 17.2073 13.7432C17.1608 13.6195 17.0902 13.5063 16.9997 13.4101Z"
                  fill="#1B1B1C"
                />
              </svg>
            )}
          </span>

          {CategoryObj.map((elm, index) => {
            const state = index === 1 ? anlyticsButton : marketing;
            const updateState = index === 1 ? setAnlyticsButton : setMarketingButton;

            return (
              <CategoryContainer
                obj={elm}
                index={index}
                currentState={state}
                updateState={updateState}
                setCurrentSection={setCategorySection}
                currentSection={categorySection}
                translations={translations}
              />
            );
          })}
        </div>
        {!templateTwo && (
          <div className={styles?.lastButton || ''}>
            <Button
              onClick={() => handleAcceptCookies()}
              btnText={translate(translations, 'cookie_confirm_button', 'Confirm my choices')}
              isInternalLink={false}
              buttonType="primary"
              buttonSize={buttonSize}
              gtmClass="cookie-consent-gtm btn-cta"
            />
          </div>
        )}
      </div>
    </div>
  );
};

CookieModal.propTypes = {
  ck: PropTypes.bool,
  handleAcceptCookies: PropTypes.func,
  handleDeclineCookies: PropTypes.func,
  closeModal: PropTypes.func,
  logo: PropTypes.string,
  buttonSize: PropTypes.string,
  declineButtonType: PropTypes.string,
  templateTwo: PropTypes.bool,
  cookieLink: PropTypes.shape({
    title: PropTypes.string,
    path: PropTypes.string,
  }),
  hide: PropTypes.bool,
};

export default CookieModal;
