/* eslint-disable no-unused-vars */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable react/no-danger */
/* eslint-disable no-nested-ternary */
/* eslint-disable no-unused-expressions */
import React, { useState, useRef, useContext } from 'react';
import { MdClose } from '@react-icons/all-files/md/MdClose';
import PropTypes from 'prop-types';
import { Context } from 'gatsby-core-theme/src/context/MainProvider';
import { translate, getUrl } from 'gatsby-core-theme/src/helpers/getters';
import Button from '../../atoms/newsletter/toggle-button/index';
import Form from '../../atoms/newsletter/form/index';
import styles from './newsletter.module.scss';

const Newsletter = ({ page, openBtnText = 'Unlock Bonuses', footer = false, isSticky = true }) => {
  const [toggleNewsetter, setToggleNewsletter] = useState(false);
  const [isClicked, setIsClicked] = useState(false);
  const { translations } = useContext(Context) || {};
  const redirectUrl =
    page?.path === '/'
      ? `${getUrl(page?.path)}?subscribed=true`
      : `${getUrl(page?.path)}/?subscribed=true`;

  const newsletterFloatingContainer = useRef(React.createRef());
  const ppcPage = page?.template === 'ppc';

  const statesCombined = () => {
    setToggleNewsletter(!toggleNewsetter);
    setIsClicked(true);
  };

  // form

  return (
    <div
      ref={newsletterFloatingContainer}
      className={
        footer
          ? styles.contentFooter || ''
          : !isSticky
          ? styles.contentPage || ''
          : styles.content || ''
      }
    >
      {!footer && isSticky && (
        <Button
          active={!toggleNewsetter}
          text={translate(translations, 'newsletter_open_btn', openBtnText)}
          toggleNewsLetter={statesCombined}
          isClicked={isClicked}
          gtmClass="newsletter-gtm btn-cta"
          ppcPage={ppcPage}
        />
      )}
      {toggleNewsetter && (
        <div
          className={styles?.layer || ''}
          onClick={() => setToggleNewsletter(false)}
          aria-hidden="true"
        />
      )}
      <div
        className={
          footer
            ? styles.formFooter || ''
            : !isSticky
            ? styles?.formPage || ''
            : `${styles?.form || ''} ${toggleNewsetter ? styles?.active || '' : ''} ${
                ppcPage ? styles?.ppcPageForm || '' : ''
              }`
        }
      >
        <Form redirectUrl={redirectUrl} ppcPage={ppcPage} footer={footer} />
        {!footer && isSticky ? (
          <MdClose
            className={styles?.closeBtn || ''}
            onClick={() => setToggleNewsletter(false)}
            title="Close Icon"
          />
        ) : null}
      </div>
    </div>
  );
};

Newsletter.propTypes = {
  openBtnText: PropTypes.string,
  page: PropTypes.shape({
    path: PropTypes.string,
    template: PropTypes.string,
    type: PropTypes.string,
  }),
  footer: PropTypes.bool,
  isSticky: PropTypes.bool,
};

export default Newsletter;
