/* eslint-disable import/no-extraneous-dependencies */
import React, { useContext, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { navigate } from 'gatsby';
import Modal from 'gatsby-core-theme/src/hooks/modal';
import { ModalContext } from 'gatsby-core-theme/src/hooks/modal/modalContext';
import Button from '~atoms/button/button';
import { translate } from '~helpers/getters';
import { Context } from '~context/MainProvider';
import { setCookie, getCookie } from '~helpers/cookies';
import styles from './cookie-consent.module.scss';

const CookieConsent = ({
  acceptText = 'Accept',
  settingsCookie = false,
  declineText = 'Decline',
  children,
}) => {
  const cookieName = 'CookieConsent';
  const { translations } = useContext(Context) || {};

  const [showCookieConsent, setShowCookieConsent] = useState(false);

  // when user declines
  const handleDecline = () => {
    setCookie(cookieName, false, 365, '/');
    setCookie('showCookie', false, 365, '/');
    setShowCookieConsent(false);
  };
  // when user accepts
  const handleAccept = () => {
    setCookie(cookieName, true, 365, '/');
    setCookie('showCookie', false, 365, '/');
    setShowCookieConsent(false);
  };

  useEffect(() => {
    if (typeof window !== `undefined` && getCookie('showCookie') !== 'false') {
      setShowCookieConsent(true);
    }
  }, []);

  return (
    <div className={`${styles.cookieConsent || ''} ${(showCookieConsent && styles.show) || ''}`}>
      <div className={styles.content || ''}>{children}</div>
      <div className={styles.buttonsContainer || ''}>
        {settingsCookie && (
          <Modal>
            <Button
              btnText={translate(translations, 'cookie_setting_button', 'Cookie Setting')}
              isInternalLink={false}
              buttonType="terti"
              buttonSize="m"
              gtmClass="cookie-consent-gtm btn-cta"
            />
          </Modal>
        )}

        <Button
          onClick={() => handleAccept()}
          btnText={translate(translations, 'cookie_accept_button', acceptText)}
          isInternalLink={false}
          buttonType="primary"
          buttonSize="m"
          gtmClass="cookie-consent-gtm btn-cta"
        />

        {declineText && (
          <Button
            onClick={() => handleDecline()}
            btnText={translate(translations, 'cookie_decline_button', declineText)}
            isInternalLink={false}
            buttonType="secondary"
            buttonSize="m"
            gtmClass="cookie-consent-gtm btn-cta"
          />
        )}
      </div>
    </div>
  );
};

CookieConsent.propTypes = {
  acceptText: PropTypes.string,
  settingsCookie: PropTypes.bool,
  declineText: PropTypes.string,
  declineURL: PropTypes.string,
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node, PropTypes.any]),
};

export default CookieConsent;
