// IMPORT MODULES
import React, { useState, useContext } from 'react';
import { LanguageContext } from '../../backend/LanguageContext';
import { UserContext } from '../../backend/UserContext';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
// IMPORT IMAGES
import next from '../../icons/next.svg';
import next_reverse from '../../icons/next-reverse.svg';
// import arrow from "../../icons/arrow.svg";

const schema = z.object({
  name: z.string().min(1),
  surname: z.string().min(1),
});

const AcceptStage = ({
  setStage,
  recepientAmount,
  creditDuration,
  cardDetails,
  setCardDetails,
  borrowerData,
  guaranterData,
  isGuranter,
  setAcceptedMessage,
  setUserDataRes,
  userDataRes,
  setErrMessage,
  setErrMessageEn,
  setErrMessageTkm,
}) => {
  const { locale } = useContext(LanguageContext);
  const userToken = localStorage.getItem('userToken');
  const { user } = useContext(UserContext);

  const handleCardDetails = (e) => {
    setCardDetails(e.target.value);
  };

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

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      amount: recepientAmount ? recepientAmount : 'Loading',
      duration: creditDuration ? creditDuration : 'loading',
    },
  });

  const loanCreateCheck = async () => {
    try {
      const response = await fetch(
        'https://shahsyotag.halkbank.gov.tm/onlineloancre-services/api/loancre/check',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json, text/plain',
            'Content-Type': 'application/json;charset=UTF-8',
          },
          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 jsonedResponse = await response.json();

      if (jsonedResponse.errCode === 0) {
        // sendCode();
      } else {
        setErrMessage(jsonedResponse.messageRu);
        setErrMessageTkm(jsonedResponse.message);
        setErrMessageEn(jsonedResponse.messageEn);
        setStage(10);
      }
    } catch (error) {}
  };

  const sendCode = async () => {
    try {
      const response = await fetch('https://shahsyotag.halkbank.gov.tm/sendOTP', {
        method: 'POST',
        headers: { 'Content-Type': 'aplication/json' },
        body: JSON.stringify({
          phone_number: user.mobile_phone,
        }),
      });

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

      if (response.status !== 200 || response.status !== 201) {
        console.log(response.status);
      }

      setStage(9);
    } catch (error) {
      console.error(error);
    }
  };

  const onSubmit = () => {
    loanCreateCheck();
  };

  if (error) {
    return (
      <section className="cs-1 err-section">
        <h1 className="cs-2-title">
          {errorMessage}
          {locale === 'TKM'
            ? ' Bir zat  ýalňyş ...'
            : locale === 'РУС'
            ? ' Ошибка...'
            : locale === 'ENG'
            ? 'Error...'
            : ' Bir zat  ýalňyş ...'}
        </h1>
        <br />
        <button type="button" className="sign-btn reg-btn" onClick={() => setStage(7)}>
          <div>
            <div className="btn-img">
              <img src={next_reverse} alt="logout" />
            </div>
            <h3>
              {locale === 'TKM'
                ? 'Yza'
                : locale === 'РУС'
                ? 'Назад'
                : locale === 'ENG'
                ? 'Back'
                : 'Yza'}
            </h3>
          </div>
        </button>
      </section>
    );
  }

  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 onSubmit={handleSubmit(onSubmit)}>
        <h2 className="cs-2-title">
          {locale === 'TKM'
            ? 'Karzyň maglumatlaryny tassyklaň'
            : locale === 'РУС'
            ? 'Подтвердите данные кредита'
            : locale === 'ENG'
            ? 'Confirm the loan details'
            : 'Karzyň maglumatlaryny tassyklaň'}
        </h2>
        <div className="imm-credit-form-wrapper">
          <div className="input-block">
            <label htmlFor="amount">
              {locale === 'TKM'
                ? 'Karzyň möçberi'
                : locale === 'РУС'
                ? 'Сумма кредита'
                : locale === 'ENG'
                ? 'Amount of loan'
                : 'Karzyň möçberi'}
            </label>
            <input {...register('amount')} type="text" id="amount" disabled />
            {errors.amount && <span>{errors.amount.message}</span>}
          </div>
          <div className="input-block">
            <label htmlFor="surname">
              {locale === 'TKM'
                ? 'Karzyň möhleti'
                : locale === 'РУС'
                ? 'Срок кредита'
                : locale === 'ENG'
                ? 'Term of loan'
                : 'Karzyň möhleti'}
            </label>
            <input {...register('duration')} type="text" id="duration" disabled />
            {errors.duration && <span>{errors.duration.message}</span>}
          </div>
          <div className="input-block">
            <label htmlFor="code">
              {locale === 'TKM'
                ? 'Karz kartynyň hasabyny dolduryň'
                : locale === 'РУС'
                ? 'Заполните счет кредитной карты'
                : locale === 'ENG'
                ? 'Fill the credit card account number'
                : 'Karz kartynyň hasabyny dolduryň'}
            </label>
            <input
              value={cardDetails}
              onChange={handleCardDetails}
              type="text"
              id="code"
              placeholder="6435980023168745"
            />
            <span className="another-option" onClick={() => setStage(12)}>
              {locale === 'TKM'
                ? 'Kartyňyz ýok bolsa, täze karty üçin ýüz tutuň'
                : locale === 'РУС'
                ? 'Оформите новую карту, если она у вас отсувствует'
                : locale === 'ENG'
                ? 'Apply for a new card if you do not have one'
                : 'Kartyňyz ýok bolsa, täze karty üçin ýüz tutuň'}
            </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(7)}>
            <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
            type="submit"
            className="sign-btn cu-btn"
            disabled={cardDetails.length !== 23 && !isLoading ? true : false}
            onClick={() => {
              onSubmit();
            }}>
            <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 AcceptStage;
