// IMPORT MODULES
import React, { useState, useRef, 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 Select from "../global/Select";
// import arrow from "../../icons/arrow.svg";

// const schema = z.object({
//   passportNumber: z.string().refine((value) => value.length === 6, {
//     message: "Passport number must be a 6-digit value",
//   }),
//   bankAccount: z.string().refine((value) => /^\d{9,18}$/.test(value), {
//     message: "Invalid bank account number",
//   }),
// });

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",
];
// 478992
// 23908934160170143144000

const BorrowerStage = ({
  setStage,
  isGuranter,
  setIsGuranter,
  setSignRecipient,
  setBorrowerData,
  setMaxAmount,
  setRecepientAmount,
  setErrMessage,
  modalOpen,
  setErrMessageEn,
  setErrMessageTkm,
}) => {
  const { locale } = useContext(LanguageContext);

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

  const [idSerial, setIdSerial] = useState("I-AS");
  const [passportNumber, setPassportNumber] = useState("");
  const [accNumber, setAccNumber] = useState("");

  const handlePassportNumber = (e) => {
    setPassportNumber(e.target.value);
  };
  const handleAcctNumber = (e) => {
    setAccNumber(e.target.value);
  };

  const isGuranterHandler = (value) => {
    setIsGuranterSelected(true);
    setIsGuranter(value);
  };

  const checkboxHandleChange = (e) => {
    e.target.value === "guaranter" ? setIsGuranter(true) : setIsGuranter(false);
  };

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

  const fetchData = async (idSeria, idNo, accountNo, clientType, stage) => {
    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,
            accountNo: accountNo,
            clientType: "recipient",
          }),
        }
      );

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

      const responseJson = await response.json();

      setSignRecipient(responseJson.signRecipient);
      setRecepientAmount(responseJson.availableAmount);
      setMaxAmount(responseJson.availableAmount);
      setErrCode(await responseJson.errCode);
      setBorrowerData(responseJson);

      setIsLoading(false);
      // responseJson.errCode === 0 ? setStage(2) : setStage(3);
      if (responseJson.errCode === 0) {
        setStage(2);
      } else if (responseJson.errCode !== 0) {
        setErrMessage(responseJson.messageRu);
        setErrMessageEn(responseJson.messageEn);
        setErrMessageTkm(responseJson.message);
        setStage(3);
      }
    } catch (error) {
      // setStage(3);
      setIsLoading(false);

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

  const onSubmit = (data) => {
    fetchData(idSerial, passportNumber, accNumber, isGuranter);
  };

  useEffect(() => {
    setIsGuranterSelected(false);
  }, [modalOpen]);

  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 (err) {
  //   return (
  //     <section className="imm-cs-1">
  //       <h1 className="cs-2-title">Failed to fetch...</h1>
  //       <div className="cu-bottom cd-2-title">
  //         <button type="button" className="sign-btn reg-btn" onClick={onSubmit}>
  //           <div>
  //             <div className="btn-img">
  //               <img src={next_reverse} alt="logout" />
  //             </div>
  //             <h3>
  //               {locale === 'TKM'
  //                 ? 'Yza'
  //                 : locale === 'РУС'
  //                 ? 'Заново'
  //                 : locale === 'ENG'
  //                 ? 'Back'
  //                 : 'Yza'}
  //             </h3>
  //           </div>
  //         </button>
  //       </div>
  //     </section>
  //   );
  // }

  return (
    <section className="imm-cs-1 cs-1">
      <form onSubmit={handleSubmit(onSubmit)}>
        <h2 className="cs-2-title">
          {locale === "TKM"
            ? "Maglumatlary dolduryň"
            : locale === "РУС"
            ? "Заполните данные"
            : locale === "ENG"
            ? "Fill in the details"
            : "Maglumatlary 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="number"
              id="passport-number"
              required
            />
            {/* {passportNumber.length !== 6 && <span>It should be 6 digits</span>} */}
          </div>
          <div className="input-block">
            <label htmlFor="bank-acc">
              {locale === "TKM"
                ? "Aýlyk kartyň hasaby"
                : locale === "РУС"
                ? "Счет зарплатной карты"
                : locale === "ENG"
                ? "Salary card account"
                : "Aýlyk kartyň hasaby"}
            </label>
            <input
              // {...register("bankAccount", { valueAsNumber: true })}
              value={accNumber}
              onChange={handleAcctNumber}
              type="number"
              id="bank-acc"
              required
            />
            {/* {accNumber.length !== 23 && <span>It should be 23 digits</span>} */}

            {/* {errors.bankAccount && <span>{errors.bankAccount.message}</span>} */}
          </div>
        </div>

        <div className="imm-credit-checkbox-wrapper">
          <h3>
            {locale === "TKM"
              ? "Zamunçylygyň görnüşini saýlan"
              : locale === "РУС"
              ? "Выберите вид поручителя"
              : locale === "ENG"
              ? "Select the type of guarantor"
              : "Zamunçylygyň görnüşini saýlan"}
          </h3>
          <div className="imm-credit-checkbox-group">
            <div
              className="imm-credit-checkbox-block"
              onClick={() => isGuranterHandler(false)}
            >
              <input
                type="radio"
                id="borrower"
                value={"recepient"}
                name="client-type"
                checked={
                  isGuranterSelected ? (isGuranter ? false : true) : false
                }
                onChange={checkboxHandleChange}
                // {...register("clientType")}
                className="radio-button"
              />
              <label htmlFor="borrower">
                {locale === "TKM"
                  ? "Ätiýaçlandyryş hyzmaty"
                  : locale === "РУС"
                  ? "Гос. страхование"
                  : locale === "ENG"
                  ? "Insurance Service "
                  : "Ätiýaçlandyryş hyzmaty"}
              </label>
            </div>

            <div
              className="imm-credit-checkbox-block"
              onClick={() => isGuranterHandler(true)}
            >
              <input
                type="radio"
                id="isGuranter"
                value={"guaranter"}
                name="client-type"
                checked={
                  isGuranterSelected ? (isGuranter ? true : false) : false
                }
                onChange={checkboxHandleChange}
                // {...register("clientType")}
                className="radio-button"
              />
              <label htmlFor="isGuranter">
                {locale === "TKM"
                  ? "Zamunçy"
                  : locale === "РУС"
                  ? "Поручитель"
                  : locale === "ENG"
                  ? "The guarantor"
                  : "Zamunçy"}
              </label>
            </div>
          </div>
        </div>

        <div className="card-button cs-1-bottom">
          <button
            disabled={
              passportNumber.length === 6 &&
              accNumber.length === 23 &&
              isGuranterSelected
                ? false
                : true
            }
            type="submit"
            className="sign-btn cd-btn"
            onClick={() => {
              // setData({ ...data, type: inputValid, type_localized: input });
            }}
          >
            <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 BorrowerStage;
