// IMPORT MODULES
import React, { useState, useContext, useEffect } from 'react';
import { LanguageContext } from '../../backend/LanguageContext';
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 { UserContext } from '../../backend/UserContext';
// import arrow from "../../icons/arrow.svg";

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

const PhoneAccept = ({
  paymentDetails,
  borrowerData,
  submitCardDetails,
  paymentLink,
  setStage,
  isGuranter,
  guaranterData,
  recepientAmount,
  cardDetails,
  creditDuration,
  setAcceptedMessage,
  recipientWorkPlace,
  recipientWorkPosition,
  availableAmount,
}) => {
  const { locale } = useContext(LanguageContext);
  const { user } = useContext(UserContext);
  const userToken = localStorage.getItem('userToken');

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

  const [invalidData, setInvalidData] = useState(false);
  const [tryAgain, setTryAgain] = useState(false);

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

  const [errMessage, setErrMessage] = useState();

  const [messageSend, setMessageSend] = useState(false);
  const [timeLeft, setTimeLeft] = useState(0);

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

  const { register, handleSubmit } = useForm({
    resolver: zodResolver(schema),
  });

  // ///////////////////Card registration

  const confirmPayment = async () => {
    try {
      const headers = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      };

      const formData = new URLSearchParams();
      formData.append('app', 'sanlykarz');
      formData.append('id', borrowerData.idNo);
      formData.append('md-order', paymentDetails['md-order']);
      formData.append('acs-req-id', submitCardDetails['acs-request-id']);
      formData.append('acs-session-url', submitCardDetails['acs-session-url']);
      formData.append('otp', codeValue);
      formData.append('term-url', submitCardDetails['terminate-url']);

      const response = await fetch('https://shahsyotag.halkbank.gov.tm/api/v1/confirm-payment', {
        method: 'POST',
        headers: headers,
        body: formData.toString(),
      });

      const jsonedResponse = await response.json();

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

      if (jsonedResponse.status === 'ok' && jsonedResponse['final-url'].includes('status=1')) {
        console.log(jsonedResponse['final-url']);
        setInvalidData(false);
        checkPayment();
      } else if (
        jsonedResponse.status === 'wrong-otp' ||
        !jsonedResponse['final-url'].includes('status=1')
      ) {
        setTryAgain(true);
      } else {
        setInvalidData(true);
      }
    } catch (error) {}
  };

  const checkPayment = async () => {
    try {
      const response = await fetch(
        `https://shahsyotag.halkbank.gov.tm/app/api/check-payment-credit-card?paymentId=${paymentLink.id}&orderId=${paymentDetails['md-order']}&status=1`,
      );

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

      const jsonedResponse = await response.json();

      if (jsonedResponse.status.ErrorCode === '0') {
        console.log('success');
        loanCreateCheck();
      }
    } catch (error) {
      console.error(error.toString());
    }
  };

  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 {
        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) {
        setErrMessage(response.status);
        setError(true);
        throw new Error(`HTTP error! Status: ${response.status}`);
      }

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

  // ///////////////////Loan creating

  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,
        }),
      });

      const jsonedResponse = await response.json();

      if (jsonedResponse === 'OTP validated successfully') {
        loanCreate();
      } else {
        setErrMessage(true);
      }
    } catch (error) {}
  };

  const loanCreate = 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) {
        sendData(responseJson);
      } else {
        setErrMessage(responseJson.messageRu);
        setStage(10);
      }
    } catch (error) {
      console.error(error.toString());
      // Handle errors as needed
      setError(true);
    }
  };

  const sendData = async (requestBody) => {
    try {
      const headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${userToken}`,
      };
      const response = await fetch('https://shahsyotag.halkbank.gov.tm/app/api/quick_loans', {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({
          sign: requestBody.sign,
          where_works: recipientWorkPlace,
          position: recipientWorkPosition,
          mobile_phone: user.mobile_phone,
          name: borrowerData.name,
          surname: borrowerData.surname,
        }),
      });

      const jsonedResponse = await response.json();
      if (!cardDetails) {
      }

      setAcceptedMessage(jsonedResponse.message);
      setIsLoading(false);

      setStage(11);
    } catch (error) {
      console.error(error.toString());
      setError(true);
    }
  };

  const codeResend = 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);
        throw new Error(`HTTP error! Status: ${response.status}`);
      }

      if (response.status !== 200 || response.status !== 201) {
        setMessageSend(true);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const startTimer = () => {
    setTimeLeft(30); // Set initial time
    const intervalId = setInterval(() => {
      setTimeLeft((prevTimeLeft) => {
        if (prevTimeLeft === 1) {
          clearInterval(intervalId);
          setMessageSend(false); // Reset messageSend state after timer finishes
        }
        return prevTimeLeft - 1;
      });
    }, 1000);
  };

  useEffect(() => {
    if (messageSend) {
      startTimer();
    }
  }, [messageSend]);

  const onSubmit = (data) => {
    if (cardDetails) {
      confirmCode();
    } else {
      confirmPayment();
    }
  };

  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>
    );
  }

  if (error) {
    return (
      <section className="cs-1 err-section">
        <h1 className="cs-2-title">
          {errMessage}
          {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(8)}>
          <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>
    );
  }

  return (
    <section className="imm-cs-1 cs-1">
      <form onSubmit={handleSubmit(onSubmit)}>
        <h2 className="cs-2-title">
          {locale === 'TKM'
            ? `${
                cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number']
              } Karz ýüzlenmäni tassyklamak üçin belgä iberilen SMS duýduryş koduny giriziň`
            : locale === 'РУС'
            ? `Для подтверждения кредитной заявки, введите код с СМС оповещения, отправленный на номер ${
                cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number']
              }`
            : locale === 'ENG'
            ? `To confirm the loan application enter the SMS alert code sent to the number ${
                cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number']
              }`
            : `${
                cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number']
              } Karz ýüzlenmäni tassyklamak üçin belgä iberilen SMS duýduryş koduny giriziň`}
        </h2>
        <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" />
            <button
              type="button"
              disabled={messageSend}
              className="another-option"
              onClick={codeResend}>
              Отправить код снова
            </button>
            {messageSend && <p>Time left: {timeLeft} seconds</p>}
            {/* {errors.code && <span>{errors.code.message}</span>} */}
          </div>
        </div>
        {invalidData && (
          <section className=" cs-1">
            <h1 className="cs-2-title">
              {locale === 'TKM'
                ? 'Ýalňyş, maglumatlary barlaň'
                : locale === 'РУС'
                ? 'Ошибка, проверьте данные'
                : locale === 'ENG'
                ? 'Error, check data'
                : 'Ýalňyş, maglumatlary barlaň'}
            </h1>
          </section>
        )}
        {tryAgain && (
          <section className="imm-cs-1 cs-1">
            <h1 className="cs-2-title">
              {' '}
              {locale === 'TKM'
                ? 'Gaýtadan iberip görüň'
                : locale === 'РУС'
                ? 'Попробуйте отправить снова'
                : locale === 'ENG'
                ? 'Try sending again'
                : 'Gaýtadan iberip görüň'}
            </h1>
          </section>
        )}
        <div className="cu-bottom cd-2-title">
          <button
            type="submit"
            className="sign-btn reg-btn"
            onClick={() => (cardDetails ? setStage(8) : setStage(13))}>
            <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={
              cardDetails
                ? codeValue.length !== 6 && !isLoading
                  ? true
                  : false
                : codeValue.length !== 5 && !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 PhoneAccept;
