/* eslint-disable no-nested-ternary */
import React, { useState, useContext, useRef } from 'react';
import PropTypes from 'prop-types';
import { MdClose } from '@react-icons/all-files/md/MdClose';
import { AiOutlineQuestionCircle } from '@react-icons/all-files/ai/AiOutlineQuestionCircle';

import { translate } from 'gatsby-core-theme/src/helpers/getters';
import Button from 'gatsby-core-theme/src/components/atoms/button/button';
import { Context } from 'gatsby-core-theme/src/context/MainProvider';
// eslint-disable-next-line import/no-extraneous-dependencies
import loadable from '@loadable/component';

import styles from './wagering-calculator.module.scss';
import { getRecommendedToplist } from '../../../helpers/common';

const WageringCalculator = ({
  mainTitle = 'Wagering Requirement Calculator',
  infoIcon,
  infoTitle = 'Example: 20x Wagering Requirement',
  infoText = 'Lorem ipsum dolor sit amet consectetur. Pharetra sed etiam placerat interdum ut. Pretium ipsum ultrices interdum condimentum nullam. Suscipit augue placerat laoreet hendrerit dui euismod quam rutrum. Magna in luctus egestas massa erat. Lorem ipsum dolor sit amet consectetur. Pharetra sed etiam placerat interdum ut. Pretium ipsum ultrices interdum condimentum nullam. Suscipit augue placerat laoreet hendrerit dui euismod quam rutrum. Magna in luctus egestas massa erat. Lorem ipsum dolor sit amet consectetur. Pharetra sed etiam placerat interdum ut. Pretium ipsum ultrices interdum condimentum nullam. Suscipit augue placerat laoreet hendrerit dui euismod quam rutrum. Magna in luctus egestas massa erat. Lorem ipsum dolor sit amet consectetur. Pharetra sed etiam placerat interdum ut. Pretium ipsum ultrices interdum condimentum nullam. Suscipit augue placerat laoreet hendrerit dui euismod quam rutrum. Magna in luctus egestas massa erat.',
  pageContext = {},
  buttonType = 'primary',
}) => {
  const wgcContribution = useRef(null);
  const wgcBonus = useRef(null);
  const wgcCalcSelect = useRef(null);
  const wgcDeposit = useRef(null);
  const wgcWagering = useRef(null);

  const [isInfoOpen, setIsInfoOpen] = useState(false);
  const [showRecommendedOperators, setShowRecommendedOperators] = useState(false);
  const [result, setResult] = useState(null);
  const { translations } = useContext(Context);
  const InfoIcon = infoIcon || AiOutlineQuestionCircle;
  const operators = pageContext.marketSections?.recommended_casinos?.modules?.length
    ? getRecommendedToplist(pageContext.marketSections)
    : [];

  const ReccommendedCasinos =
    operators.length > 0 && loadable(() => import('../../atoms/recommended-operators'));

  const Calculate = () => {
    // eslint-disable-next-line
    wgcContribution.current.value && (wgcContribution.current.value = 100);

    setResult(
      Math.round(
        (Number(wgcBonus.current.value) +
          (wgcCalcSelect.current.value !== 'bonus' ? Number(wgcDeposit.current.value) : 0)) *
          Number(wgcWagering.current.value) *
          (100 / Number(wgcContribution.current.value))
      )
    );
    setShowRecommendedOperators(true);
  };

  return (
    <div>
      <div className={styles.container}>
        <form target="_self">
          <span className={styles.mainTitle}>
            {translate(translations, 'wagecalc_main_title', mainTitle)}
            {infoTitle && infoText && (
              <InfoIcon
                onClick={() => {
                  setIsInfoOpen(true);
                }}
                title="Question Icon"
              />
            )}
          </span>
          <div className={styles.inputContainer}>
            <label className={styles.label} htmlFor="wgc_deposit">
              {translate(translations, 'wagecalc_deposit_amount', 'Deposit amount')}
            </label>
            <input
              id="wgc_deposit"
              className={styles.input}
              ref={wgcDeposit}
              type="number"
              min={0}
            />
          </div>
          <div className={styles.inputContainer}>
            <label className={styles.label} htmlFor="bonus">
              {translate(translations, 'wagecalc_bonus_amount', 'Bonus amount')}
            </label>
            <input
              className={styles.input}
              ref={wgcBonus}
              type="number"
              min={0}
              required
              id="bonus"
            />
          </div>
          <div className={styles.inputContainer}>
            <label className={styles.label} htmlFor="wagering">
              {translate(translations, 'wagecalc_wagering', 'Wagering')}
            </label>
            <input
              className={styles.input}
              ref={wgcWagering}
              type="number"
              min={0}
              required
              id="wagering"
            />
          </div>
          <div className={styles.inputContainer}>
            <select
              id="wgcCalcSelect"
              className={styles.select}
              ref={wgcCalcSelect}
              onChange={({ target }) => {
                const deposit = document.getElementById('wgc_deposit');
                deposit.required = target.value !== 'bonus';
                deposit.checkValidity();
              }}
              aria-label={translate(translations, 'wagecalc_select_label', 'Select an option')}
            >
              <option value="bonus">{translate(translations, 'wagecalc_bonus', 'Bonus')}</option>
              <option value="bonus_deposit">
                {translate(translations, 'wagecalc_deposit_bonus', 'Deposit + Bonus')}
              </option>
            </select>
          </div>

          <div className={styles.inputContainer}>
            <label className={styles.label} htmlFor="contribution">
              {translate(translations, 'wagecalc_contribution', 'Contribution %')}
            </label>
            <input
              className={styles.input}
              ref={wgcContribution}
              type="number"
              min={0}
              max={100}
              id="contribution"
            />
          </div>

          <Button
            onClick={Calculate}
            btnText={translate(translations, 'wagecalc_calculate', 'Calculate')}
            isInternalLink={false}
            buttonType={buttonType}
            buttonSize="m"
          />

          {!!result && !isInfoOpen && (
            <div className={styles.resultContainer}>
              <span>{translate(translations, 'wagecalc_result', 'Results:')}</span>
              <span>
                {translate(translations, 'wagecalc_result_currency', '€')}
                {result}
              </span>
            </div>
          )}
        </form>
        {isInfoOpen && (
          <div className={styles.info}>
            <h2 className={styles.infoTitle}>
              {translate(translations, 'wagecalc_info_title', infoTitle)}
            </h2>
            <MdClose
              onClick={() => {
                setIsInfoOpen(false);
              }}
              title="Close Icon"
            />
            <p className={styles.infoText}>
              {translate(translations, 'wagecalc_info_text', infoText)}
            </p>
          </div>
        )}
        {ReccommendedCasinos && showRecommendedOperators && (
          <ReccommendedCasinos
            title={translate(
              translations,
              'wagecalc_recommended_casinos',
              'Recommeded Casinos for you: '
            )}
            operators={operators}
          />
        )}
      </div>
    </div>
  );
};

WageringCalculator.propTypes = {
  mainTitle: PropTypes.string,
  infoTitle: PropTypes.string,
  infoText: PropTypes.string,
  infoIcon: PropTypes.element,
  buttonType: PropTypes.string,
  pageContext: PropTypes.shape({
    marketSections: PropTypes.shape({}),
  }),
};

export default WageringCalculator;
