/* eslint-disable react/jsx-key */
/* eslint-disable no-undef */
/* eslint-disable react/jsx-no-undef */

// TODO: eliminate usage of Form, Checkbox, and RadioButtonGroup so these components can be deleted from the repo

import React, {useState} from 'react';
import {PropTypes} from 'prop-types';
import classNames from 'classnames';
import {Form} from 'display-library/Form';
import {Checkbox} from 'display-library/Checkbox';
import {Link} from 'display-library/Link';
import {ModalPopup} from 'display-library/ModalPopup';
import {RadioButtonGroup} from 'display-library/RadioButtonGroup';
import ModalBuilder from './modal_builder';
import {performLoyaltyRewardsSignUp} from 'rewards/actions';
import LoadingOverlay from 'shared/components/loader/overlay';
import {getViewType} from 'shared/utils/site_utils';

import './account_rewards_page.scss';

export const AccountRewardsPage = props => {
  const [justEnrolled, setSignedInJustEnrolled] = useState(
    window && window.location.hash == '#join#justEnrolled'
  );
  const [showModal, setShowModal] = useState(false || justEnrolled);
  const [agreeToTerms, setAgreeToTerms] = useState(false);
  const [redTerms, setRedTerms] = useState(false);
  const [isSignupInProgress, setIsSignupInProgress] = useState(false);
  const [emailError, setEmailError] = useState(emailError);
  const [selectedGender, setSelectedGender] = useState('women');

  /* Needed this because closeModal was passed in as an object and
     not as a function into ModalBuilder */
  const newProps = {
    ...props,
    closeModal: () => {
      setShowModal(false);
      if (window.location.hash.includes('#justEnrolled')) {
        setSignedInJustEnrolled(false);
        window.location.hash = '';
      }
    }
  };
  /* Handle just enrolled user. used url hash to differentiate */
  if (!props.is_user_login && justEnrolled) window.location.reload();

  //Requires fixing the new login
  const web_library_auth = false;
  /* Currently Hide this section until the business wants it back */
  const show_join_our_list = false;

  return (
    <LoadingOverlay
      show={isSignupInProgress}
      label="Signing You Up"
      labelPosition="top"
    >
      <section
        className="AccountRewardsPage__account-rewards-page"
        id="AccountRewardsPage"
      >
        {showModal && (
          <ModalPopup className="AccountRewardsPage__modal" show>
            <ModalBuilder props={newProps} justEnrolled={justEnrolled} />
          </ModalPopup>
        )}
        <section className="AccountRewardsPage__rewarding-great-taste">
          <div className="AccountRewardsPage__rewarding-great-taste-text-container">
            <h6>MODA REWARDS</h6>
            <div className="rewarding">Rewarding</div>
            <div className="exceptional">Exceptional Taste</div>
            <div className="members">
              Members of Moda Rewards earn purchase rewards points and other
              exclusive perks. Get {props.rewards_data.bonus_points} bonus
              points when you sign up.
            </div>
            <h5
              className={classNames('AccountRewardsPage__to-start', {
                red: redTerms
              })}
            >
              To start earning Moda Rewards points, please agree to our &nbsp;
              <Link
                name="Terms & Conditions."
                theme="underline"
                href="/terms"
                target="_blank"
              />
            </h5>
            <Form
              submitButtonClassName={[
                'rewards-button',
                !web_library_auth && agreeToTerms && !props.is_user_login
                  ? ' joinLink is-logged-out-user'
                  : ''
              ]}
              width="300px"
              showSubmitButton
              submitButtonValue="JOIN NOW"
              errorMessage={agreeToTerms}
              onSubmit={() =>
                handleSignUp(
                  agreeToTerms,
                  setShowModal,
                  setIsSignupInProgress,
                  web_library_auth,
                  setRedTerms,
                  props
                )
              }
              inputs={[
                <Checkbox
                  defaultChecked={false}
                  label="YES, I AGREE TO"
                  name="checkbox"
                  useCheckmark
                  checked={agreeToTerms}
                  onChange={() => {
                    setRedTerms(false);
                    setAgreeToTerms(!agreeToTerms);
                  }}
                />,
                <Link
                  name="TERMS & CONDITIONS"
                  theme="underline"
                  href="/terms"
                  target="_blank"
                />
              ]}
            />
          </div>
        </section>
        <section className="AccountRewardsPage__how-it-works">
          <div className="AccountRewardsPage__what-youll-enjoy-header">
            HOW IT WORKS
          </div>
          <section className="AccountRewardsPage__first">
            <section className="AccountRewardsPage__join">
              <h2>
                1.
                <p /> Join the Program
              </h2>
              <h5>
                Signing up is free & easy. Just sign-in to your Moda account (or
                create one), and enroll here.{'\n'}
                <p />
                You&apos;ll get {props.rewards_data.bonus_points} bonus points
                just for joining.
              </h5>
            </section>
            <section className="AccountRewardsPage__shop">
              <h2>
                2.
                <p /> Shop To Earn
              </h2>
              <h5>
                Once you&apos;re enrolled, most purchases you make will
                automatically add Rewards points to your account.{'\n'}
                <p />
                Visit your Account Center to track your redeemable points.
              </h5>
            </section>
            <section className="AccountRewardsPage__redeem">
              <h2>
                3.
                <p /> Redeem Your Rewards
              </h2>
              <h5>
                For every {props.rewards_data.threshold_point} points you earn,
                a {props.rewards_data.currency_symbol}
                {props.rewards_data.threshold_amount} Reward will be added to
                your account.{'\n'}
                <p /> You can redeem Rewards during Checkout on any order.
              </h5>
            </section>
          </section>
          <h6>
            *Please enroll in Moda Rewards with your preferred currency
            selected.{'\n'} Rewards can only be redeemed using the currency in
            which they were earned. See{' '}
            <Link
              className="AccountRewardsPage__faq"
              name="FAQ"
              theme="underline"
              href="https://help.modaoperandi.com/hc/en-us"
              target="_blank"
            />{' '}
            for more information.
          </h6>
        </section>
        <section
          className={classNames('AccountRewardsPage__what-youll-enjoy', {
            'hide-border': !show_join_our_list
          })}
        >
          <div className="AccountRewardsPage__what-youll-enjoy-header">
            WHY JOIN MODA REWARDS
          </div>
          <section className="AccountRewardsPage__second">
            <section className="AccountRewardsPage__points">
              <h2>Points On Purchases</h2>
              <h5>
                You&apos;ll earn 1 point for every{' '}
                {props.rewards_data.currency_display} spent, and receive{' '}
                {props.rewards_data.currency_symbol}
                {props.rewards_data.threshold_amount} in Moda Rewards every time
                you reach {props.rewards_data.threshold_point} points.
              </h5>
            </section>
            <section className="AccountRewardsPage__exclusive">
              <h2>Advance Access</h2>
              <h5>
                Get a first look at new arrivals and receive special offers
                ahead of anyone else.
              </h5>
            </section>
            <section className="AccountRewardsPage__inside">
              <h2>Insider Updates</h2>
              <h5>
                Never miss a moment with exclusive updates and special surprises
                delivered throughout the year.
              </h5>
            </section>
          </section>
        </section>
        {show_join_our_list && (
          <section className="AccountRewardsPage__join-our-list">
            <section className="AccountRewardsPage__join-our-list-text">
              <div className="AccountRewardsPage__join-our-list-text-div">
                {getViewType() == 'desktop' ? (
                  <>
                    <div>JOIN OUR LIST FOR DAILY STYLE</div>
                    <div>INSPIRATION & FIRST ACCESS:</div>
                  </>
                ) : (
                  <>
                    <div>
                      JOIN OUR LIST FOR DAILY STYLE INSPIRATION & FIRST ACCESS:
                    </div>
                  </>
                )}
              </div>
              {getViewType() == 'desktop' && (
                <div className="AccountRewardsPage__join-our-list-opt">
                  To opt-out of email sharing or to view our Privacy Policy,{' '}
                  <Link
                    className="AccountRewardsPage__privacy-policy"
                    name="click here."
                    theme="underline"
                    href="/privacy"
                    target="_blank"
                  />
                </div>
              )}
            </section>
            <section className="AccountRewardsPage__join-our-list-form">
              <Form
                parentId="AccountRewardsPage"
                setParentData={data => {
                  convertGender(
                    data['gender-preference'] &&
                      data['gender-preference'].value,
                    setSelectedGender
                  );
                }}
                inputs={[
                  <RadioButtonGroup
                    name="gender-preference"
                    labels={['women', 'men']}
                    values={['WOMENSWEAR', 'MENSWEAR']}
                    default="women"
                  />
                ]}
              />
              <EmailSignup
                setEmailError={setEmailError}
                rendered_by="Rewards"
                gender={selectedGender}
              />
              {getViewType() == 'mobile' && (
                <div className="AccountRewardsPage__join-our-list-opt">
                  To opt-out of email sharing or to view our Privacy Policy,{' '}
                  <Link
                    className="AccountRewardsPage__privacy-policy"
                    name="click here."
                    theme="underline"
                    href="/privacy"
                    target="_blank"
                  />
                </div>
              )}
            </section>
          </section>
        )}
      </section>
    </LoadingOverlay>
  );
};

const handleSignUp = (
  agreeToTerms,
  setShowModal,
  setIsSignupInProgress,
  web_library_auth,
  setRedTerms,
  props
) => {
  if (!agreeToTerms) {
    setRedTerms(true);
  } else {
    setRedTerms(false);
    if (
      typeof SiteConstants !== 'undefined' &&
      SiteConstants.current_user == null
    ) {
      if (agreeToTerms) {
        onSignUp(web_library_auth);
      }
    } else if (agreeToTerms) {
      if (!props.is_employee && !props.is_enrolled && props.is_user_login) {
        enrollUser(setIsSignupInProgress).then(setShowModal(true));
      } else if (props.is_employee || props.is_enrolled) {
        setShowModal(true);
      }
    }
  }
};

const onSignUp = web_library_auth => {
  try {
    if (web_library_auth) {
      SiteStore.dispatch(WebLibrary.authentication.actions.showLoginModal());
      SiteStore.dispatch(
        WebLibrary.authentication.actions.setLoginModalTab('register')
      );
    }
  } catch (e) {
    console.log(e);
  }
};

const enrollUser = async setIsSignupInProgress => {
  setIsSignupInProgress(true);
  await performLoyaltyRewardsSignUp(SiteConstants.current_user);
  setIsSignupInProgress(false);
};

const convertGender = (value, setSelectedGender) => {
  if (value == 'WOMENSWEAR') {
    setSelectedGender('women');
  } else if (value == 'MENSWEAR') {
    setSelectedGender('men');
  }
};

AccountRewardsPage.propTypes = {
  change_currency_enroll_rewards_path: PropTypes.string,
  controller_used: PropTypes.bool,
  currency_code: PropTypes.string,
  is_employee: PropTypes.bool,
  is_enrolled: PropTypes.bool,
  is_user_login: PropTypes.bool,
  rewards_data: PropTypes.object,
  gender_preference: PropTypes.string,
  onSignUp: PropTypes.func
};

export default AccountRewardsPage;
