// 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";

const CardRegistration = ({
  borrowerData,
  setStage,
  setPaymentLink,
  setPaymentDetails,
  invalidData,
}) => {
  const { locale } = useContext(LanguageContext);
  const userToken = localStorage.getItem("userToken");

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

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    // resolver: zodResolver(schema),
    defaultValues: {
      name: borrowerData.name ? borrowerData.name : "Loading",
      surname: borrowerData.surname ? borrowerData.surname : "Loading",
      lastname: borrowerData.lastname ? borrowerData.lastname : "loading",
      passportSerial: borrowerData.idSeria ? borrowerData.idSeria : "Loading",
      passportNumber: borrowerData.idNo ? borrowerData.idNo : "Loading",
      birthDate: borrowerData.birthDate ? borrowerData.birthDate : "Loading",
      passDate: borrowerData.passDate ? borrowerData.passDate : "Loading",
      passOrg: borrowerData.passOrg ? borrowerData.passOrg : "Loading",
      workPlace: borrowerData.workPlace ? borrowerData.workPlace : "",
      workPosition: borrowerData.workPosition ? borrowerData.workPosition : "",
      address: borrowerData.address ? borrowerData.address : "",
    },
  });

  const [workPlace, setWorkPlace] = useState("");
  const [workPosition, setWorkPosition] = useState("");
  const [address, setAddress] = useState("");

  console.log(borrowerData);

  const handleWorkPlace = (e) => {
    setWorkPlace(e.target.value);
  };
  const handleWorkPosition = (e) => {
    setWorkPosition(e.target.value);
  };
  const handleAdress = (e) => {
    setAddress(e.target.value);
  };

  const sendData = async () => {
    try {
      const headers = {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${userToken}`,
      };
      const response = await fetch(
        "https://shahsyotag.halkbank.gov.tm/app/api/online_credit_card",
        {
          method: "POST",
          headers: headers,
          body: JSON.stringify({
            id_seria: borrowerData.idSeria,
            id_no: borrowerData.idNo,
            name: borrowerData.name,
            lastname: borrowerData.lastname,
            surname: borrowerData.surname,
            birth_date: borrowerData.birthDate,
            pass_date: borrowerData.passDate,
            pass_org: borrowerData.passOrg,
            dep_code: borrowerData.depCode,
            address: address,
          }),
        }
      );

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

      const jsonedResponse = await response.json();

      sendPaymentRequest(jsonedResponse.url);

      setPaymentLink(jsonedResponse);
    } catch (error) {
      console.error(error.toString());
    }
  };

  const sendPaymentRequest = async (link) => {
    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("url", link);

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

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

      const jsonedResponse = await response.json();

      setPaymentDetails(jsonedResponse);

      setStage(13);

      setIsLoading(false);
    } catch (error) {
      console.error(error.toString());
      setError(true);
    }
  };

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

  if (error) {
    return (
      <section className="imm-cs-1 cs-1">
        <h1 className="cs-2-title">Error...</h1>
        <div className="cu-bottom cd-2-title">
          <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>
        </div>
      </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()}>
        <h2 className="cs-2-title">
          {locale === "TKM"
            ? "Karz kartyny açdyrmak üçin maglumatlary tassyklaň"
            : locale === "РУС"
            ? "Подтвердите данные для оформления кредитной карты"
            : locale === "ENG"
            ? "Please confirm the personal data for openning the credit card"
            : "Karz kartyny açdyrmak üçin maglumatlary tassyklaň"}
        </h2>
        <div className="imm-credit-form-wrapper">
          <div className="input-block">
            <label htmlFor="name">
              {locale === "TKM"
                ? "Ady"
                : locale === "РУС"
                ? "Имя"
                : locale === "ENG"
                ? "Name"
                : "Ady"}
            </label>
            <input {...register("name")} type="text" id="name" disabled />
          </div>
          <div className="input-block">
            <label htmlFor="lastname">
              {locale === "TKM"
                ? "Familiýa"
                : locale === "РУС"
                ? "Фамилия"
                : locale === "ENG"
                ? "Lastname"
                : "Familiýa"}
            </label>
            <input
              {...register("lastname")}
              type="text"
              id="lastname"
              disabled
            />
            {/* {errors.surname && <span>{errors.surname.message}</span>} */}
          </div>
          <div className="input-block">
            <label htmlFor="surname">
              {locale === "TKM"
                ? "Atasynyň ady"
                : locale === "РУС"
                ? "Отчество"
                : locale === "ENG"
                ? "Middle name"
                : "Atasynyň ady"}
            </label>
            <input {...register("surname")} type="text" id="surname" disabled />
          </div>
          <div className="input-block">
            <label htmlFor="birthDate">
              {locale === "TKM"
                ? "Doglan senesi"
                : locale === "РУС"
                ? "Дата рождения"
                : locale === "ENG"
                ? "Date of birth"
                : "Doglan senesi"}
            </label>
            <input
              {...register("birthDate")}
              type="text"
              id="birthDate"
              disabled
            />
          </div>
          <div className="input-block">
            <label htmlFor="passDate">
              {locale === "TKM"
                ? "Pasport berlen senesi"
                : locale === "РУС"
                ? "Дата выдачи паспорта"
                : locale === "ENG"
                ? "Passport issue date"
                : "Pasport berlen senesi"}
            </label>
            <input
              {...register("passDate")}
              type="text"
              id="passDate"
              disabled
            />
          </div>
          <div className="input-block">
            <label htmlFor="passOrg">
              {locale === "TKM"
                ? "Pasport berlen ýeri"
                : locale === "РУС"
                ? "Кем выдан паспорт"
                : locale === "ENG"
                ? "Passport issued by"
                : "Pasport berlen ýeri"}
            </label>
            <input {...register("passOrg")} type="text" id="passOrg" disabled />
          </div>

          {/* <div className="input-block">
            <label htmlFor="workPlace">
              {locale === 'TKM'
                ? 'At'
                : locale === 'РУС'
                ? 'Место работы'
                : locale === 'ENG'
                ? 'amount'
                : 'At'}
            </label>
            <input
              {...register('workPlace')}
              value={workPlace}
              onChange={handleWorkPlace}
              type="text"
              id="workPlace"
              placeholder=""
            />
          </div>
          <div className="input-block">
            <label htmlFor="workPosition">
              {locale === 'TKM'
                ? 'At'
                : locale === 'РУС'
                ? 'Должность'
                : locale === 'ENG'
                ? 'amount'
                : 'At'}
            </label>
            <input
              {...register('workPosition')}
              value={workPosition}
              onChange={handleWorkPosition}
              type="text"
              id="workPosition"
              placeholder=""
            />
          </div> */}
          <div className="input-block">
            <label htmlFor="address">
              {locale === "TKM"
                ? "Ýaşaýan salgysy "
                : locale === "РУС"
                ? "Адрес прописки "
                : locale === "ENG"
                ? "Address of residence "
                : "Ýaşaýan salgysy "}
            </label>
            <input
              disabled={true}
              {...register("address")}
              type="text"
              id="address"
            />
          </div>
        </div>

        {invalidData && (
          <section className="imm-cs-1 cs-1">
            <h1 className="cs-2-title">
              {locale === "TKM"
                ? "Kard maglumatlary barlamana we täzeden girizmäne haýyş edýäris"
                : locale === "РУС"
                ? "Пожалуйста, проверьте и еще раз введите данные своей карты."
                : locale === "ENG"
                ? "Please check and re-enter your card details"
                : "Kard maglumatlary barlamana we täzeden girizmäne haýyş edýäris"}
            </h1>
          </section>
        )}

        <div className="cu-bottom cd-2-title">
          <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>
          <button
            type="submit"
            className="sign-btn cu-btn"
            disabled={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 CardRegistration;
