// IMPORT MODULES
import React, { useState, useContext } 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 Select from '../global/Select';

// const schema = z.object({
//   passportNumber: z
//     .number()
//     .int()
//     .gte(100000, { message: "Must be equal to 6 digits" })
//     .lte(999999, { message: "Must be equal to 6 digits" }),
//   bankAccount: z
//     .number()
//     .int()
//     .gte(10000000000000000000000, { message: "Must be equal to 23 digits" })
//     .lte(99999999999999999999999, { message: "Must be equal to 23 digits" }),
//   // clientType: z.string(),
// });

const IDSerias = [
  'I-AS',
  'I-AH',
  'I-BN',
  'I-LB',
  'I-MR',
  'I-DZ',
  'II-AS',
  'II-AH',
  'II-BN',
  'II-LB',
  'II-MR',
  'II-DZ',
];

const GuaranterStage = ({
  setStage,
  signRecipient,
  setGuaranterData,
  setSignGuaranter,
  setErrMessage,
  setErrMessageEn,
  setErrMessageTkm,
  borrowerData,
}) => {
  const { locale } = useContext(LanguageContext);

  const [isLoading, setIsLoading] = useState(false);
  const [err, setErr] = useState(false);
  const [errCode, setErrCode] = useState();

  const [idSerial, setIdSerial] = useState('I-AS');
  const [passportNumber, setPassportNumber] = useState('');
  const [cardMaskNumber, setCardMaskNumber] = useState('');

  const [paymentCardDurationYear, setPaymentCardDurationYear] = useState('');
  const [paymentCardDurationMonth, setPaymentCardDurationMonth] = useState('');

  const handlePassportNumber = (e) => {
    setPassportNumber(e.target.value);
  };
  const handleAccMaskNumber = (e) => {
    setCardMaskNumber(e.target.value);
  };

  function maskString(str) {
    if (str.length !== 16) {
      throw new Error('String length must be 16.');
    }

    const firstPart = str.slice(0, 6);
    const middlePart = '*'.repeat(6);
    const lastPart = str.slice(12);

    return firstPart + middlePart + lastPart;
  }

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

  const clientInfoRequest = async (idSeria, idNo, cardMaskNumber, setErrMessage) => {
    try {
      setIsLoading(true);
      const response = await fetch(
        `https://shahsyotag.halkbank.gov.tm/onlineloan-services/api/clientinfo`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            idSeria: idSeria,
            idNo: idNo,
            cardMaskNumber: maskString(cardMaskNumber),
            clientType: 'guarantor',
            signRecipient: signRecipient,
            availableAmount: borrowerData.availableAmount,
            expDate: `${paymentCardDurationMonth}/${paymentCardDurationYear}`,
          }),
        },
      );

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

      const responseJson = await response.json();

      setSignGuaranter(responseJson.signGuaranter);

      setErrCode(responseJson.errCode);

      setErrMessage(responseJson.messageRu);

      setGuaranterData(responseJson);

      setIsLoading(false);

      if (responseJson.errCode === 0) {
        setStage(5);
      } else if (responseJson.errCode !== 0) {
        setErrMessage(responseJson.messageRu);
        setErrMessageEn(responseJson.messageEn);
        setErrMessageTkm(responseJson.message);
        setStage(6);
      }
    } catch (error) {
      setIsLoading(false);

      console.error(error.toString());
      // Handle errors as needed
      setErr(true);
    }
  };

  const handlePaymentCardDurationYear = (e) => {
    setPaymentCardDurationYear(e.target.value);
  };
  const handlePaymentCardDurationMonth = (e) => {
    setPaymentCardDurationMonth(e.target.value);
  };

  const onSubmit = (data) => {
    clientInfoRequest(idSerial, passportNumber, cardMaskNumber, setErrMessage);
  };

  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'
            ? 'Zamunçynyň maglumatlaryny dolduryň'
            : locale === 'РУС'
            ? 'Заполните данные поручителя'
            : locale === 'ENG'
            ? 'Fill in the guarantor’s details'
            : 'Zamunçynyň maglumatlaryny dolduryň'}
        </h2>
        <div className="imm-credit-form-wrapper">
          <Select
            items={IDSerias}
            customId={'card'}
            blockName={'card-1-select'}
            elName={'card-1-select-el'}
            name={'passportSerial'}
            eTarget={true}
            register={register}
            label={
              locale === 'TKM'
                ? 'Pasportyň seriýasy'
                : locale === 'РУС'
                ? 'Серия паспорта'
                : locale === 'ENG'
                ? 'Passport Series'
                : 'Pasportyň seriýasy'
            }
            stateSetter={setIdSerial}
          />

          <div className="input-block">
            <label htmlFor="passport-number">
              {locale === 'TKM'
                ? 'Pasportyň belgisi'
                : locale === 'РУС'
                ? 'Номер паспорта'
                : locale === 'ENG'
                ? 'Passport number'
                : 'Pasportyň belgisi'}
            </label>
            <input
              // {...register("passportNumber", { valueAsNumber: true })}
              value={passportNumber}
              onChange={handlePassportNumber}
              type="text"
              id="passport-number"
            />
            {/* {errors.passportNumber && (
              <span>{errors.passportNumber.message}</span>
            )} */}
          </div>
          <div className="input-block">
            <label htmlFor="bank-acc">
              {locale === 'TKM'
                ? 'Bank kart belgisi'
                : locale === 'РУС'
                ? 'Номер банковсой карты'
                : locale === 'ENG'
                ? 'Bank card number'
                : 'Bank kart belgisi'}
            </label>
            <input
              // {...register("bankAccount", { valueAsNumber: true })}
              value={cardMaskNumber}
              onChange={handleAccMaskNumber}
              type="text"
              id="bank-acc"
            />
            {/* {errors.bankAccount && <span>{errors.bankAccount.message}</span>} */}
          </div>

          <div className="input-block">
            <label htmlFor="duration-month">
              {locale === 'TKM'
                ? 'Kartyň möhleti (aý)'
                : locale === 'РУС'
                ? 'Срок годности карты (месяц)'
                : locale === 'ENG'
                ? 'Card expiration date (month)'
                : 'Kartyň möhleti (aý)'}
            </label>
            <input
              value={paymentCardDurationMonth}
              onChange={handlePaymentCardDurationMonth}
              type="number"
              id="duration-month"
              placeholder="08"
            />
            {/* {errors.code && <span>{errors.code.message}</span>} */}
          </div>
          <div className="input-block">
            <label htmlFor="duration-year">
              {locale === 'TKM'
                ? 'Kartyň möhleti (ýyl)'
                : locale === 'РУС'
                ? 'Срок годности карты (год)'
                : locale === 'ENG'
                ? 'Card expiration date (year)'
                : 'Kartyň möhleti (ýyl)'}
            </label>
            <input
              value={paymentCardDurationYear}
              onChange={handlePaymentCardDurationYear}
              type="number"
              id="duration-year"
              placeholder="42"
            />
            {/* {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(2)}>
            <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"
            disabled={
              passportNumber.length === 6 &&
              cardMaskNumber.length === 16 &&
              paymentCardDurationMonth.length === 2 &&
              paymentCardDurationYear.length === 2
                ? false
                : true
            }
            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 GuaranterStage;
