// IMPORT MODULES
import React, { useState, useEffect, useContext } from 'react';
import { LanguageContext } from '../../backend/LanguageContext';

// IMPORT COMPONENTS
import CustomSelect from '../global/CustomSelect';

// IMPORT IMAGES
import credit from '../../images/credit-card.jpg';
import next from '../../icons/next.svg';

const CardStage1 = ({ setStage, data, setData, cardData, req, setReq }) => {
  const { locale } = useContext(LanguageContext);
  const [price, setPrice] = useState(0);
  const [input, setInput] = useState(data.selected_card ? data.selected_card : false);
  const [inputValid, setInputValid] = useState(
    data.selected_card_localized ? data.selected_card_localized : false,
  );
  const [id, setId] = useState(1);
  const [img, setImg] = useState(credit);
  useEffect(() => {
    if (inputValid !== '' && cardData) {
      cardData.data.map((el) => {
        if (
          Object.values(el).includes(inputValid) ||
          Object.values(
            JSON.parse(el.translations.find((els) => els.locale === 'ru').attribute_data),
          ).includes(inputValid) ||
          Object.values(
            JSON.parse(el.translations.find((els) => els.locale === 'en').attribute_data),
          ).includes(inputValid)
        ) {
          setId(el.id);
          setPrice(el.card_cost);
          setReq({
            TKM: el.documents,
            RUS: JSON.parse(el.translations.find((els) => els.locale === 'ru').attribute_data)
              .documents,
            ENG: JSON.parse(el.translations.find((els) => els.locale === 'en').attribute_data)
              .documents,
          });
        }
      });
    }
  }, [inputValid, cardData]);

  useEffect(() => {
    if (cardData) {
      cardData.data.map((el) => {
        if (el.id === id) {
          setImg(el.image.path);
          setInput(el.name);
        }
      });
    }
  }, [id]);

  return (
    <section className="card-stage-1">
      <form>
        <div className="input-block">
          <label htmlFor="card">
            {locale === 'TKM'
              ? 'Kartyň görnüşini saýlaň'
              : locale === 'РУС'
              ? 'Выберите вид карты'
              : locale === 'ENG'
              ? 'Choose card type'
              : 'Kartyň görnüşini saýlaň'}
          </label>
          <CustomSelect
            items={
              cardData
                ? locale === 'ENG'
                  ? cardData.data.map((el) =>
                      el.translations.find((els) => els.locale === 'en')
                        ? JSON.parse(
                            el.translations.find((els) => els.locale === 'en').attribute_data,
                          ).name
                        : '',
                    )
                  : locale === 'РУС'
                  ? cardData.data.map((el) =>
                      el.translations.find((els) => els.locale === 'ru')
                        ? JSON.parse(
                            el.translations.find((els) => els.locale === 'ru').attribute_data,
                          ).name
                        : '',
                    )
                  : locale === 'TKM'
                  ? cardData.data.map((el) => el.name)
                  : cardData.data.map((el) => el.name)
                : ['']
            }
            customId={'card'}
            blockName={'card-1-select'}
            elName={'card-1-select-el'}
            name={'card-type'}
            stateSetter={(e) => {
              setInputValid(e);
            }}
            eTarget={true}
            placeholder={
              locale === 'TKM'
                ? 'Kartyň görnüşi'
                : locale === 'РУС'
                ? 'Вид карты'
                : locale === 'ENG'
                ? 'Card type'
                : 'Kartyň görnüşi'
            }
            defaultValue={inputValid}
          />
        </div>
        <div className="card-description">
          <div className="cd-top">
            <div className="cd-img">
              <img src={img} alt="card" />
            </div>
            <div className="cd-text">
              <h2>
                HalkBank -{' '}
                {cardData
                  ? locale === 'ENG'
                    ? cardData.data.map((el) =>
                        el.id === id
                          ? el.translations.find((els) => els.locale === 'en')
                            ? JSON.parse(
                                el.translations.find((els) => els.locale === 'en').attribute_data,
                              ).name
                            : ''
                          : '',
                      )
                    : locale === 'РУС'
                    ? cardData.data.map((el) =>
                        el.id === id
                          ? el.translations.find((els) => els.locale === 'ru')
                            ? JSON.parse(
                                el.translations.find((els) => els.locale === 'ru').attribute_data,
                              ).name
                            : ''
                          : '',
                      )
                    : locale === 'TKM'
                    ? cardData.data.map((el) => (el.id === id ? el.name : ''))
                    : cardData.data.map((el) => (el.id === id ? el.name : ''))
                  : locale === 'TKM'
                  ? 'Aýlyk karty'
                  : locale === 'РУС'
                  ? 'Зарплатная карта'
                  : locale === 'ENG'
                  ? 'Salary card'
                  : 'Aýlyk karty'}
              </h2>
              <h3>
                {cardData
                  ? locale === 'ENG'
                    ? cardData.data.map((el) =>
                        el.id === id
                          ? el.translations.find((els) => els.locale === 'en')
                            ? JSON.parse(
                                el.translations.find((els) => els.locale === 'en').attribute_data,
                              ).text
                            : ''
                          : '',
                      )
                    : locale === 'РУС'
                    ? cardData.data.map((el) =>
                        el.id === id
                          ? el.translations.find((els) => els.locale === 'ru')
                            ? JSON.parse(
                                el.translations.find((els) => els.locale === 'ru').attribute_data,
                              ).text
                            : ''
                          : '',
                      )
                    : locale === 'TKM'
                    ? cardData.data.map((el) => (el.id === id ? el.text : ''))
                    : cardData.data.map((el) => (el.id === id ? el.text : ''))
                  : locale === 'TKM'
                  ? 'Müşderiniň bankymyzdan alan karz pul serişdeleri “Karz kartyna geçirilýär . Müşderi “Karz karty” bank karty üsti bilen ähli nagt däl hasaplaşyk töleglerini amala aşyrýar.'
                  : locale === 'РУС'
                  ? 'Банковская карта, на которую зачисляется заработная плата клиента. Открывается на основании договора между банком и предприятием. Эта карта предоставляет полный перечень услуг по безналичному платежу в терминалах, перевод денежных средств с одной зарплатной карты на другую, а также получению наличных денежных средств в банкоматах на территории Туркменистана.'
                  : locale === 'ENG'
                  ? "A bank card to which the client's salary is credited. It is opened on the basis of an agreement between the bank and the enterprise. This card provides a full range of services for non-cash payment in terminals, transfer of funds from one payroll card to another, as well as cash withdrawal from ATMs in Turkmenistan."
                  : 'Müşderiniň bankymyzdan alan karz pul serişdeleri “Karz kartyna geçirilýär . Müşderi “Karz karty” bank karty üsti bilen ähli nagt däl hasaplaşyk töleglerini amala aşyrýar.'}
              </h3>
            </div>
          </div>
          <div className="cd-bottom">
            <div className="cd-bottom-content">
              <h3>
                {locale === 'TKM'
                  ? 'Kartyň möhleti'
                  : locale === 'РУС'
                  ? 'Срок действия карты'
                  : locale === 'ENG'
                  ? 'Card expiry date'
                  : 'Kartyň möhleti'}
              </h3>
              <h2>
                {cardData
                  ? cardData.data.map((el) => {
                      if (el.id === id) {
                        if (el.term === 1 || el.term === '1') {
                          return `${el.term} ${
                            locale === 'TKM'
                              ? 'ýyl'
                              : locale === 'РУС'
                              ? 'год'
                              : locale === 'ENG'
                              ? 'year'
                              : 'ýyl'
                          }`;
                        } else if (
                          el.term === 2 ||
                          el.term === '2' ||
                          el.term === 3 ||
                          el.term === '3' ||
                          el.term === 4 ||
                          el.term === '4'
                        ) {
                          return `${el.term} ${
                            locale === 'TKM'
                              ? 'ýyl'
                              : locale === 'РУС'
                              ? 'года'
                              : locale === 'ENG'
                              ? 'years'
                              : 'ýyl'
                          }`;
                        } else {
                          return `${el.term} ${
                            locale === 'TKM'
                              ? 'ýyl'
                              : locale === 'РУС'
                              ? 'лет'
                              : locale === 'ENG'
                              ? 'years'
                              : 'ýyl'
                          }`;
                        }
                      }
                    })
                  : '30'}
              </h2>
            </div>
            <div className="cd-bottom-content">
              <h3>
                {locale === 'TKM'
                  ? 'Göterim'
                  : locale === 'РУС'
                  ? 'Процентная ставка'
                  : locale === 'ENG'
                  ? 'Interest rate'
                  : 'Göterim'}{' '}
              </h3>
              <h2>
                {' '}
                {cardData
                  ? cardData.data.map((el) => (el.id === id ? el.interest_rate : ''))
                  : '0'}{' '}
                %
              </h2>
            </div>
            <div className="cd-bottom-content">
              <h3>
                {locale === 'TKM'
                  ? 'Kartyň bahasy (GBüS bilen)'
                  : locale === 'РУС'
                  ? 'Стоимость карты  (с учётом НДС)'
                  : locale === 'ENG'
                  ? 'Card cost (with VAT)'
                  : 'Kartyň bahasy (GBüS bilen)'}
              </h3>
              <h2>
                {' '}
                {cardData
                  ? cardData.data.map((el) => (el.id === id ? el.card_cost : ''))
                  : '28.75'}{' '}
                {locale === 'TKM'
                  ? 'manat'
                  : locale === 'РУС'
                  ? 'маната'
                  : locale === 'ENG'
                  ? 'manats'
                  : 'manat'}
              </h2>
            </div>
          </div>
        </div>
        <div className="card-button">
          <button
            type="button"
            disabled={!inputValid}
            className="sign-btn cd-btn"
            onClick={() => {
              setStage(2);
              setData({
                ...data,
                selected_card: input,
                selected_card_localized: inputValid,
                price: price,
              });
            }}>
            <div>
              <h3>
                {locale === 'TKM'
                  ? 'Dowam et'
                  : locale === 'РУС'
                  ? 'Продолжить'
                  : locale === 'ENG'
                  ? 'Proceed'
                  : 'Dowam et'}
              </h3>
              <div className="btn-img">
                <img src={next} alt="logout" />
              </div>
            </div>
          </button>
        </div>
      </form>
    </section>
  );
};

export default CardStage1;
