// 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 arrow from "../../icons/arrow.svg";

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

const PaymentDetails = ({
  setStage,
  paymentDetails,
  borrowerData,
  setSumbitCardDetails,
  paymentLink,
  setInvalidData,
}) => {
  const { locale } = useContext(LanguageContext);

  const [timeLeft, setTimeLeft] = useState(paymentDetails['remaining-time']);

  const [paymentName, setPaymentName] = useState('');
  const [paymentCard, setPaymentCard] = useState('');
  const [paymentCv, setPaymentCv] = useState('');
  const [paymentCardDurationYear, setPaymentCardDurationYear] = useState('');
  const [paymentCardDurationMonth, setPaymentCardDurationMonth] = useState('');

  const handlePaymentCard = (e) => {
    setPaymentCard(e.target.value);
  };
  const handlePaymentName = (e) => {
    setPaymentName(e.target.value.toUpperCase());
  };
  const handlePaymentCv = (e) => {
    setPaymentCv(e.target.value);
  };
  const handlePaymentCardDurationYear = (e) => {
    setPaymentCardDurationYear(e.target.value);
  };
  const handlePaymentCardDurationMonth = (e) => {
    setPaymentCardDurationMonth(e.target.value);
  };

  useEffect(() => {
    const interval = setInterval(() => {
      if (timeLeft > 0) {
        setTimeLeft(timeLeft - 1);
      }
    }, 1000);

    return () => clearInterval(interval);
  }, [timeLeft]);

  const sendPaymentRequest = 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('card-number', paymentCard.toString());
      formData.append(
        'card-expiry',
        '20' + paymentCardDurationYear.toString() + paymentCardDurationMonth.toString(),
      );
      formData.append('name-on-card', paymentName);
      formData.append('card-cvc', paymentCv.toString());

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

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

      const jsonedResponse = await response.json();

      if (jsonedResponse.status === 'ok') {
        setSumbitCardDetails(jsonedResponse);
        setInvalidData(false);
        setStage(14);
      } else {
        setStage(12);

        setInvalidData(true);
      }

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

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

  const onSubmit = (data) => {
    sendPaymentRequest();
  };

  if (timeLeft <= 0) {
    setStage(12);
  }

  return (
    <section className="imm-cs-1 cs-1">
      <form onSubmit={handleSubmit(onSubmit)}>
        <h2 className="cs-2-title">
          {locale === 'TKM'
            ? 'Töleg üçin kartyň maglumatlaryny giriziň'
            : locale === 'РУС'
            ? 'Введите данные карты для оплаты'
            : locale === 'ENG'
            ? 'Enter card details for payment'
            : 'Töleg üçin kartyň maglumatlaryny giriziň'}
        </h2>
        <div className="payment-details">
          <h2>
            {locale === 'TKM'
              ? 'Tölemeli mukdar:'
              : locale === 'РУС'
              ? 'Сумма к оплате:'
              : locale === 'ENG'
              ? 'Amount to pay:'
              : 'Tölemeli mukdar:'}
            {paymentDetails['amount-info']}
          </h2>
          <h2>
            {locale === 'TKM'
              ? 'Wagt galdy:'
              : locale === 'РУС'
              ? 'Оставшееся время:'
              : locale === 'ENG'
              ? 'Time left:'
              : 'Wagt galdy:'}
            {Math.floor((timeLeft % 3600) / 60)}:{timeLeft % 60}
          </h2>
        </div>
        <div className="imm-credit-form-wrapper">
          <div className="input-block">
            <label htmlFor="card">
              {locale === 'TKM'
                ? 'Kartyň ýüzünde görkezilen ady, familiýasyny giriziň'
                : locale === 'РУС'
                ? 'Имя и фамилия, указанные на карте'
                : locale === 'ENG'
                ? 'Enter first name and last name indicated on the card'
                : 'Kartyň ýüzünde görkezilen ady, familiýasyny giriziň'}
            </label>
            <input
              value={paymentName}
              onChange={handlePaymentName}
              type="text"
              id="card"
              placeholder="6435980023168745"
            />
            {/* {errors.code && <span>{errors.code.message}</span>} */}
          </div>
          <div className="input-block">
            <label htmlFor="card">
              {locale === 'TKM'
                ? 'Kart belgisi'
                : locale === 'РУС'
                ? 'Номер карты'
                : locale === 'ENG'
                ? 'Card number'
                : 'Kart belgisi'}
            </label>
            <input
              value={paymentCard}
              onChange={handlePaymentCard}
              type="number"
              id="card"
              placeholder="6435980023168745"
            />
            {/* {errors.code && <span>{errors.code.message}</span>} */}
          </div>
          {paymentDetails['is-cvc-required'] && (
            <div className="input-block">
              <label htmlFor="cvc">
                {locale === 'TKM'
                  ? 'Kartyň CVC'
                  : locale === 'РУС'
                  ? 'CVC карты'
                  : locale === 'ENG'
                  ? "Card's CVC"
                  : 'Kartyň CVC'}
              </label>
              <input
                value={paymentCv}
                onChange={handlePaymentCv}
                type="number"
                id="cvc"
                // maxLength={3}
                max={999}
                placeholder="123"
              />
              {/* {errors.code && <span>{errors.code.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(12)}>
            <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={
              paymentName.length < 4 ||
              paymentName.length > 32 ||
              paymentCard.toString().length !== 16 ||
              paymentCv.toString().length !== 3 ||
              paymentCardDurationYear.toString().length !== 2 ||
              paymentCardDurationMonth.toString().length !== 2 ||
              +paymentCardDurationMonth <= 0 ||
              +paymentCardDurationMonth > 12
                ? true
                : false
            }
            type="submit"
            className="sign-btn cu-btn"
            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 PaymentDetails;
