/* eslint-disable no-nested-ternary */
import React, { useState, useEffect } 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 Button from 'gatsby-core-theme/src/components/atoms/button/button';
import useTranslate from '~hooks/useTranslate/useTranslate';
// eslint-disable-next-line import/no-extraneous-dependencies
import RecomendedOperators from '../../atoms/recommended-operators';
import styles from './wagering-calculator.module.scss';
import { getRecommendedToplist } from '../../../helpers/common';
import wageringCalculator from '../../../helpers/wagering-calculator';
import WAGERING_INPUT_FIELDS from '../../../constants/wagering-calculator';

const WageringCalculator = ({
  mainTitle = 'Wagering RTP 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',
  modulePosition,
  currency = '€'
}) => {
  const [depositAmount, setDepositAmount] = useState('');
  const [bonusAmount, setBonusAmount] = useState('');
  const [type, setType] = useState('bonus');
  const [contribution, setContribution] = useState('');
  const [rtp, setRtp] = useState('');
  const [rolloverTerms, setRolloverTerms] = useState('');
  const [isInfoOpen, setIsInfoOpen] = useState(false);
  const [showRecommendedOperators, setShowRecommendedOperators] = useState(false);
  const [result, setResult] = useState(null);

  const InfoIcon = infoIcon || AiOutlineQuestionCircle;
  const operators = pageContext.marketSections?.recommended_casinos?.modules?.length
    ? getRecommendedToplist(pageContext.marketSections)
    : [];

  const capValue = (value, max) => {
    const num = Number(value);
    if (value === '' || Number.isNaN(num)) return value;
    return num > max ? String(max) : value;
  };

  const stateByKey = {
    depositAmount: [depositAmount, setDepositAmount],
    bonusAmount: [bonusAmount, setBonusAmount],
    contribution: [contribution, setContribution],
    rtp: [rtp, setRtp],
    rolloverTerms: [rolloverTerms, setRolloverTerms],
  };

  useEffect(() => {
    const deposit = Number(depositAmount);
    const bonus = Number(bonusAmount);
    const contrib = Number(contribution);
    const rtpVal = Number(rtp);
    const rollover = Number(rolloverTerms);

    if (bonus && contrib && rtpVal && rollover) {
      const effectiveRTP = wageringCalculator({
        depositAmount: deposit || 0,
        bonusAmount: bonus,
        type,
        contribution: contrib,
        rtp: rtpVal,
        rolloverTerms: rollover,
      });
      setResult(effectiveRTP);
      setShowRecommendedOperators(true);
    } else {
      setResult(null);
    }
  }, [depositAmount, bonusAmount, type, contribution, rtp, rolloverTerms]);

  const resetFields = () => {
    setDepositAmount('');
    setBonusAmount('');
    setType('bonus');
    setContribution('');
    setRtp('');
    setRolloverTerms('');
    setResult(null);
    setShowRecommendedOperators(false);
  };

  return (
    <div>
      <div className={styles.container}>
        <form target="_self" onSubmit={(e) => e.preventDefault()}>
          <span className={styles.mainTitle}>
            {useTranslate('wagecalc_main_title', mainTitle)}
            {infoTitle && infoText && (
              <InfoIcon
                onClick={() => {
                  setIsInfoOpen(true);
                }}
                title="Question Icon"
              />
            )}
          </span>
          {WAGERING_INPUT_FIELDS.map((field) => {
            if (field.id === 'type') {
              return (
                <div key="type" className={styles.inputContainer}>
                  <label className={styles.label} htmlFor="wgcCalcSelect">
                    {useTranslate('wagecalc_type', 'Type')}
                  </label>
                  <select
                    id="wgcCalcSelect"
                    className={styles.select}
                    value={type}
                    onChange={(e) => setType(e.target.value)}
                    aria-label={useTranslate('wagecalc_select_label', 'Select an option')}
                  >
                    <option value="bonus">{useTranslate('wagecalc_bonus', 'Bonus')}</option>
                    <option value="bonus_deposit">
                      {useTranslate('wagecalc_deposit_bonus', 'Deposit + Bonus')}
                    </option>
                  </select>
                </div>
              );
            }
            const [value, setValue] = stateByKey[field.stateKey];
            return (
              <div key={field.id} className={styles.inputContainer}>
                <label className={styles.label} htmlFor={field.id}>
                  {useTranslate(field.translationKey, field.defaultLabel)}
                </label>
                <input
                  id={field.id}
                  className={styles.input}
                  value={value}
                  onChange={(e) => setValue(
                    field.max ? capValue(e.target.value, field.max) : e.target.value,
                  )}
                  type="number"
                  min={0}
                  max={field.max}
                  required={field.required}
                />
              </div>
            );
          })}
          <Button
            onClick={resetFields}
            btnText={useTranslate('wagecalc_reset', 'Reset')}
            isInternalLink={false}
            buttonType={buttonType}
            buttonSize="m"
          />

          {!!result && !isInfoOpen && (
            <div className={styles.resultContainer}>
              <span>{useTranslate('wagecalc_result', 'Effective RTP:')}</span>
              <span>
                {currency}
                {result}
              </span>
            </div>
          )}
        </form>
        {isInfoOpen && (
          <div className={styles.info}>
            <h2 className={styles.infoTitle}>{useTranslate('wagecalc_info_title', infoTitle)}</h2>
            <MdClose
              onClick={() => {
                setIsInfoOpen(false);
              }}
              title="Close Icon"
            />
            <p className={styles.infoText}>{useTranslate('wagecalc_info_text', infoText)}</p>
          </div>
        )}
        {operators && operators.length > 0 && showRecommendedOperators && (
          <RecomendedOperators
            title={useTranslate('wagecalc_recommended_casinos', 'Recommeded Casinos for you: ')}
            operators={operators}
            pageTemplate={pageContext?.page?.template}
            modulePosition={modulePosition}
          />
        )}
      </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({}),
  }),
  modulePosition: PropTypes.number,
  currency: PropTypes.string,
};

export default WageringCalculator;
