/* eslint-disable no-unused-vars */
/* eslint-disable no-unused-expressions */
/* eslint-disable import/no-extraneous-dependencies */
import React, { useRef, useState, useEffect, useContext } from 'react';
import PropTypes from 'prop-types';
import { Context } from 'gatsby-core-theme/src/context/MainProvider';
import { translate } from 'gatsby-core-theme/src/helpers/getters';
import PrivacyandSuccess from '../privacy&button/index';
import styles from './newsletter-form.module.scss';

const NewsletterForm = ({
  handleApi,
  setErr = false,
  setLogading,
  redirectUrl,
  privacyText = 'By subscribing, you confirm that you are over 18 years of age and that you accept our',
  formText = {
    placeholderName: 'John Doe',
    placeholderEmail: 'johndoe@email.com',
    placeholderPhoneNumber: '08XXXXXXXX',
    buttonText: 'Submit',
    thankYouText: null,
    textAboveEmail: 'Email address',
    textAboveName: 'Your name',
    textAbovePhoneNumber: 'Phone number',
    mainText: 'You get more than 405 free spins',
    subscribeText: 'Subscribe to our newsletter and get more than 405 free spins instantly.',
  },
}) => {
  // eslint-disable-next-line react/destructuring-assignment

  const form = useRef(null);
  const [ip, setIP] = useState('');
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);
  const { translations } = useContext(Context) || {};

  const formTextTranslated = {
    placeholderName: translate(
      translations,
      'newsletter_form_first_name_placeholder',
      formText.placeholderName
    ),
    placeholderEmail: translate(
      translations,
      'newsletter_form_email_placeholder',
      formText.placeholderEmail
    ),
    placeholderPhoneNumber: translate(
      translations,
      'newsletter_form_phone_placeholder',
      formText.placeholderPhoneNumber
    ),
    buttonText: translate(translations, 'newsletter_form_submit', formText.buttonText),
    thankYouText: translate(translations, 'newsletter_form_thanks', formText.thankYouText),
    textAboveEmail: translate(translations, 'newsletter_form_email_text', formText.textAboveEmail),
    textAboveName: translate(
      translations,
      'newsletter_form_first_name_text',
      formText.textAboveName
    ),
    textAbovePhoneNumber: translate(
      translations,
      'newsletter_form_phone_text',
      formText.textAbovePhoneNumber
    ),
    mainText: translate(translations, 'newsletter_form_main_text', formText.mainText),
    subscribeText: translate(
      translations,
      'newsletter_form_subscribe_text',
      formText.subscribeText
    ),
  };

  const validationForm = (e) => {
    let nameValidate = false;
    let emailValidate = false;
    let numberValidate = false;

    if (!e.name.value && e.name.value.trim() === '') {
      nameValidate = false;
      e.name.classList.add(styles.error);
    } else {
      nameValidate = true;
      e.name.classList.remove(styles.error);
    }

    if (!e.phone?.value && !e.email.value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i)) {
      emailValidate = false;
      e.email.classList.add(styles.error);
    } else {
      emailValidate = true;
      e.email.classList.remove(styles.error);
    }

    if (e.phone && !e.email?.value) {
      if (!e.phone.value && e.phone.value.trim() === '') {
        numberValidate = false;
        e.phone.classList.add(styles.error);
      } else {
        numberValidate = true;
        e.phone.classList.remove(styles.error);
      }
    }

    if (nameValidate && (emailValidate || numberValidate)) {
      return true;
    }
    return false;
  };

  const getData = async () => {
    await fetch('https://geolocation-db.com/json/', {
      method: 'GET',
    })
      .then((response) => response.json())
      .then((data) => setIP(data.IPv4))
      .catch((err) => {
        // console.log(`Error ${err}`);
      });
  };

  useEffect(() => {
    getData();
  }, []);

  const bacomApi = async (name, email) => {
    // eslint-disable-next-line no-bitwise
    const timestamp = (Date.now() / 1000) | 0;
    setLoading(true);
    await fetch(
      `https://bacom.dk/subscribe/gig/?firstname=${name}&user_ip=${ip}&ref_name=${process.env.BACOM_REF_NAME}&ref_url=${process.env.BACOM_REF_URL}&timestamp=${timestamp}&country=${process.env.COUNTRY}&email=${email}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
      }
    ).then((res) =>
      res.text().then((text) => {
        text === 'OK' ? (window.location.href = redirectUrl) : setError(true);
        setLoading(false);
      })
    );
  };

  const handelSubmit = (e) => {
    if (validationForm(form.current)) {
      handleApi
        ? handleApi(form.current.name.value, form.current.email.value, ip)
        : bacomApi(form.current.name.value, form.current.email.value);
    }
  };

  return (
    <>
      {!error && !setErr ? (
        <>
          <p className={styles?.maintext || ''}>{formTextTranslated.mainText}</p>
          <p
            // eslint-disable-next-line react/no-danger
            dangerouslySetInnerHTML={{ __html: formTextTranslated.subscribeText }}
            className={styles.subscribe}
          />

          <form ref={form} onSubmit={handelSubmit}>
            {formTextTranslated.textAboveName ? (
              <label className={styles?.textAboveInput || ''} htmlFor="name">
                {formTextTranslated.textAboveName}
              </label>
            ) : null}

            <input
              className={styles.input}
              placeholder={formTextTranslated.placeholderName}
              type="text"
              name="name"
              id="name"
            />
            {formTextTranslated.textAboveEmail ? (
              <label className={styles?.textAboveInput || ''} htmlFor="email">
                {formTextTranslated.textAboveEmail}
              </label>
            ) : null}

            <input
              className={styles?.input || ''}
              placeholder={formTextTranslated.placeholderEmail}
              type="email"
              name="email"
              id="email"
            />
            {formTextTranslated.textAbovePhoneNumber ? (
              <label className={styles?.textAboveInput || ''} htmlFor="phone">
                {formTextTranslated.textAbovePhoneNumber}
              </label>
            ) : null}

            {formTextTranslated.placeholderPhoneNumber && (
              <input
                className={styles?.input || ''}
                placeholder={formTextTranslated.placeholderPhoneNumber}
                type="tel"
                name="phone"
                id="phone"
              />
            )}
            <PrivacyandSuccess
              onSubmit={() => handelSubmit()}
              loading={setLogading || loading}
              btnText={formTextTranslated.buttonText}
              privacyText={privacyText}
            />
          </form>
        </>
      ) : (
        <span>
          {translate(
            translations,
            'fail_error_newsletter',
            'Something went wrong. Please try again later!'
          )}{' '}
        </span>
      )}
    </>
  );
};
NewsletterForm.propTypes = {
  // eslint-disable-next-line react/forbid-prop-types
  formText: (PropTypes.formText = {
    placeholderName: PropTypes.string,
    placeholderEmail: PropTypes.string,
    buttonText: PropTypes.string,
    placeholderPhoneNumber: PropTypes.string,
    textAboveEmail: PropTypes.string,
    textAboveName: PropTypes.string,
    textAbovePhoneNumber: PropTypes.string,
    privacyText: PropTypes.string,
  }),
  handleApi: PropTypes.func,
  setErr: PropTypes.bool,
  redirectUrl: PropTypes.string,
  privacyText: PropTypes.string,
  setLogading: PropTypes.bool,
};

export default NewsletterForm;
