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

import next from '../../icons/next.svg';
import next_reverse from '../../icons/next-reverse.svg';
import { UserContext } from '../../backend/UserContext';

const PaymentSuccess = ({
  setStage,
  stage,
  borrowerData,
  guaranterData,
  isGuranter,
  recepientAmount,
  creditDuration,
  setErrMessage,
  setAcceptedMessage,
  setAcceptedMessageEn,
  setAcceptedMessageTkm,
}) => {
  const { locale } = useContext(LanguageContext);
  const { user } = useContext(UserContext);

  const [codeValue, setPhoneValue] = useState('');

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(false);

  const handleCodeChange = (e) => {
    setPhoneValue(e.target.value);
  };

  const confirmCode = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('https://shahsyotag.halkbank.gov.tm/validateOTP', {
        headers: { 'Content-Type': 'aplication/json' },
        method: 'POST',

        body: JSON.stringify({
          phone_number: user.mobile_phone,
          otp: codeValue,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }

      const jsonedResponse = await response.json();

      if (jsonedResponse === 'OTP validated successfully') {
        fetchData();
        setIsLoading(false);
      }
    } catch (error) {}
  };

  const fetchData = async () => {
    try {
      const response = await fetch(
        `https://shahsyotag.halkbank.gov.tm/onlineloancre-services/api/loancre`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            clientRecipient: {
              idSeria: borrowerData.idSeria,
              idNo: borrowerData.idNo,
              cardMaskNumber: borrowerData.cardMaskNumber,
              name: borrowerData.name,
              surname: borrowerData.surname,
              availableAmount: borrowerData.availableAmount,
              clientType: 'recipient',
              signRecipient: borrowerData.signRecipient,
              expDate: borrowerData.expDate,
            },
            clientGuarantor: isGuranter
              ? {
                  idSeria: guaranterData.idSeria,
                  idNo: guaranterData.idNo,
                  cardMaskNumber: guaranterData.cardMaskNumber,
                  name: guaranterData.name,
                  surname: guaranterData.surname,
                  availableAmount: guaranterData.availableAmount,
                  clientType: 'guarantor',
                  signGuarantor: guaranterData.signGuarantor,
                  expDate: guaranterData.expDate,
                }
              : null,
            availableAmount: recepientAmount,
            creditCardAccountNumber: cardDetails,
            mrtIsInsuarance: isGuranter ? 0 : 1,
            termInYears: creditDuration,
          }),
        },
      );

      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }

      const responseJson = await response.json();

      if (responseJson.errCode === 0) {
        setAcceptedMessage(responseJson.messageRu);
        setAcceptedMessageEn(responseJson.messageEn);
        setAcceptedMessageTkm(responseJson.message);
        setStage(16);
      } else {
        setErrMessage(responseJson.messageRu);
        setStage(10);
      }
    } catch (error) {
      console.error(error.toString());
      // Handle errors as needed
      setError(true);
    }
  };

  const onSubmit = (data) => {
    confirmCode();
  };

  if (isLoading) {
    return (
      <section className="loading">
        <h1 className="cs-2-title">
          {' '}
          {locale === 'TKM'
            ? 'Garaşmagyňyzy haýyş edýäris ...'
            : locale === 'РУС'
            ? 'Пожалуйста, подождите...'
            : locale === 'ENG'
            ? 'Please wait...'
            : 'Garaşmagyňyzy haýyş edýäris ...'}
        </h1>
      </section>
    );
  }

  return (
    <section className="imm-cs-1 cs-1">
      <form>
        <h2 className="succes-title">
          {locale === 'TKM'
            ? 'Karz karty açmak üçin tölegiňiz üstünlikli geçdi we arzaňyz kabul edildi '
            : locale === 'РУС'
            ? 'Оплата прошла успешно, заявка на оформление кредитной карты принята.'
            : locale === 'ENG'
            ? 'To complete the application for a Digital loan, enter the SMS code sent to the number'
            : 'Karz karty açmak üçin tölegiňiz üstünlikli geçdi we arzaňyz kabul edildi '}
        </h2>
        <h3 className="succes-sub-title">
          {locale === 'TKM'
            ? 'Sanly karz ýüz tutmaňyzy doly tamamlamak üçin siziň telefon belgiňize gelen SMS kody giriziň'
            : locale === 'РУС'
            ? 'Для завершения оформления заявки на получение быстрого кредита введите СМС код, отправленный на номер …..'
            : locale === 'ENG'
            ? 'To complete the application for a Digital loan, enter the SMS code sent to the number'
            : 'Sanly karz ýüz tutmaňyzy doly tamamlamak üçin siziň telefon belgiňize gelen SMS kody giriziň'}
        </h3>
        <div className="imm-credit-form-wrapper">
          <div className="input-block">
            <label htmlFor="code">
              {locale === 'TKM'
                ? 'Kod'
                : locale === 'РУС'
                ? 'Код'
                : locale === 'ENG'
                ? 'Code'
                : 'Kod'}
            </label>
            <input value={codeValue} onChange={handleCodeChange} type="text" id="code" />
            {/* <span className="another-option" onClick={codeResend}>
              Отправить код снова
            </span> */}
            {/* {errors.code && <span>{errors.code.message}</span>} */}
          </div>
        </div>
        <div className="cu-bottom cd-2-title">
          <button type="button" className="sign-btn reg-btn" onClick={() => setStage(14)}>
            <div>
              <div className="btn-img">
                <img src={next_reverse} alt="logout" />
              </div>
              <h3>
                {locale === 'TKM'
                  ? 'Yza'
                  : locale === 'РУС'
                  ? 'Назад'
                  : locale === 'ENG'
                  ? 'Back'
                  : 'Yza'}
              </h3>
            </div>
          </button>
          <button
            disabled={codeValue.length !== 6 && !isLoading ? true : false}
            type="submit"
            onClick={onSubmit}
            className="sign-btn cu-btn">
            <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 PaymentSuccess;
