// IMPORT MODULES
import React, { useState, useEffect, useContext } from 'react';
import { UserContext } from '../backend/UserContext';
import { LanguageContext } from '../backend/LanguageContext';
import axios from 'axios';

// IMPORT COMPONENTS
import Breadcrumb from '../components/global/Breadcrumb';
import ImmediateCreditModal from '../components/immediateCredits/ImmediateCreditModal';
import ProgressLoader from '../components/global/ProgressLoader';
import Success from '../components/global/Success';
import Error from '../components/global/Error';

// IMPORT HELPERS
import { dataDestination } from '../destinationUrl';

// IMPORT IMAGES
import credit from '../icons/credit-black.svg';
import add from '../icons/add.svg';
import allert from '../icons/info-circle.svg';

const ImmediateCredit = () => {
  const { locale } = useContext(LanguageContext);
  const [error, setError] = useState(false);
  const [success, setSuccess] = useState(false);
  const { user } = useContext(UserContext);
  const [modalOpen, setModalOpen] = useState(false);
  const [stage, setStage] = useState(1);
  const [loader, setLoader] = useState(false);
  // const [immediateCreditData, setImmediateCreditData] = useState();
  const [progress, setProgress] = useState(0);
  const userToken = localStorage.getItem('userToken');
  const [loansData, setLoansData] = useState();
  const [loanStatus, setLoanStatus] = useState();

  const [paymentDetails, setPaymentDetails] = useState();

  const [paymentCardData, setPaymentCardData] = useState();

  // console.log(userToken);

  useEffect(() => {
    if (modalOpen) {
      document.body.style.overflowY = 'hidden';
    } else {
      document.body.style.overflowY = 'visible';
    }
  }, [modalOpen]);

  const fetchData = 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/quick_loans`, {
        headers,
      });

      const jsonedResponse = await response.json();

      setLoansData(jsonedResponse);

      if (response.ok) {
        checkStatus(jsonedResponse.sign.sign);
      }

      // console.log('loan data', jsonedResponse);
    } catch (error) {
      console.error(error);
    }
  };

  const checkStatus = async (sign) => {
    try {
      const response = await fetch(
        `https://shahsyotag.halkbank.gov.tm/onlineloan-services/api/loancheck`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            sign: sign,
          }),
        },
      );

      const jsonedResponse = await response.json();

      setLoanStatus(jsonedResponse);
    } catch (error) {}
  };

  const fetchCardData = 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/get-credit-card-data`,
        {
          headers,
        },
      );

      if (!response.ok) {
        throw new Error('Err');
      }

      const jsonedResponse = await response.json();
      setPaymentCardData(jsonedResponse.data);

      // setCardData(jsonedResponse);
    } catch (error) {}
  };

  useEffect(() => {
    fetchData();
    fetchCardData();
  }, []);

  return (
    <section className="cards">
      {success ? (
        <Success
          message={
            locale === 'TKM'
              ? 'Ýüzlenme ugradyldy!'
              : locale === 'РУС'
              ? 'Ваш запрос успешно отправлен!'
              : locale === 'ENG'
              ? 'Request was successfully sent!'
              : 'Ýüzlenme ugradyldy!'
          }
          setSuccess={setSuccess}
        />
      ) : null}
      {error ? (
        <Error
          message={
            locale === 'TKM'
              ? 'Ýüzlenme ugradylmady'
              : locale === 'РУС'
              ? 'Не удалось отправить запрос'
              : locale === 'ENG'
              ? 'Failed to send request'
              : 'Ýüzlenme ugradylmady'
          }
          setError={setError}
        />
      ) : null}
      <Breadcrumb
        image={credit}
        link={'/home/immediate-credits'}
        linkTitle={
          locale === 'TKM'
            ? 'Sanly karz'
            : locale === 'РУС'
            ? 'Цифровой кредит'
            : locale === 'ENG'
            ? 'Digital loan'
            : 'Sanly karz'
        }
      />
      <ImmediateCreditModal
        setModalOpen={setModalOpen}
        modalOpen={modalOpen}
        stage={stage}
        setStage={setStage}
        loader={loader}
        setLoader={setLoader}
        setSuccess={setSuccess}
        setError={setError}
        // immediateCreditData={immediateCreditData}
        setProgress={setProgress}
      />
      {loader ? <ProgressLoader progress={progress} /> : null}
      <div className="container">
        <div className="card-title">
          <h2 className="cards-title">
            {locale === 'TKM'
              ? 'Sanly karz almak üçin onlaýn-ýüzlenme'
              : locale === 'РУС'
              ? 'Онлайн-заявка для получения цифрового кредита'
              : locale === 'ENG'
              ? 'Online application for digital loan '
              : 'Çalt karz almak üçin onlaýn-ýüzlenme'}
          </h2>
          <button
            type="button"
            className="card-btn sign-btn"
            onClick={() => {
              window.scrollTo(0, 0);
              setStage(1);
              setModalOpen(true);
            }}>
            <div className="card-img">
              <img src={add} alt="add" />
            </div>
            <h3>
              {locale === 'TKM'
                ? 'Ýüzlenme doldurmak'
                : locale === 'РУС'
                ? 'Заполнить заявку'
                : locale === 'ENG'
                ? 'Fill in application'
                : 'Ýüzlenme doldurmak'}
            </h3>
          </button>
        </div>
        <div className="loans-inner">
          <div className="home-table-wrapper">
            <table className="home-table">
              <tbody>
                <tr className="table-head">
                  <th>ID</th>
                  <th>
                    {locale === 'TKM'
                      ? 'Senesi'
                      : locale === 'РУС'
                      ? 'Дата заявки'
                      : locale === 'ENG'
                      ? 'Date'
                      : 'Senesi'}
                  </th>

                  <th>
                    {locale === 'TKM'
                      ? 'Ýagdaýy'
                      : locale === 'РУС'
                      ? 'Статус'
                      : locale === 'ENG'
                      ? 'Status'
                      : 'Ýagdaýy'}
                  </th>
                </tr>
                {loansData && loanStatus ? (
                  <tr>
                    <td>#{loansData.id}</td>
                    <td>{loansData.created_at}</td>
                    <td>
                      {locale === 'TKM'
                        ? loanStatus.message
                        : locale === 'РУС'
                        ? loanStatus.messageRu
                        : locale === 'ENG'
                        ? loanStatus.messageEn
                        : loanStatus.message}
                    </td>
                  </tr>
                ) : (
                  <tr>
                    <td>
                      {locale === 'TKM'
                        ? 'Tabşyrlan ýüzlenme ýok'
                        : locale === 'РУС'
                        ? 'Заявок на кредиты нет'
                        : locale === 'ENG'
                        ? 'There are no applications for loan issuance'
                        : 'Tabşyrlan ýüzlenme ýok'}
                    </td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {paymentCardData ? (
            <div className="home-table-wrapper">
              <h3 className="loan-card-table-title">
                {locale === 'TKM'
                  ? 'Kredit kart üçin ýüztutma'
                  : locale === 'РУС'
                  ? 'Зааявка для получения кредитной карты'
                  : locale === 'ENG'
                  ? 'Application for a credit card'
                  : 'Kredit kart üçin ýüztutma'}
              </h3>
              <table className="home-table">
                <tbody>
                  <tr className="table-head">
                    <th>ID</th>
                    <th>
                      {locale === 'TKM'
                        ? 'Görnüşi'
                        : locale === 'РУС'
                        ? 'Тип'
                        : locale === 'ENG'
                        ? 'Type'
                        : 'Görnüşi'}
                    </th>
                    <th>
                      {locale === 'TKM'
                        ? 'Senesi'
                        : locale === 'РУС'
                        ? 'Дата'
                        : locale === 'ENG'
                        ? 'Date'
                        : 'Senesi'}
                    </th>
                    <th>
                      {locale === 'TKM'
                        ? 'Ýagdaýy'
                        : locale === 'РУС'
                        ? 'Статус'
                        : locale === 'ENG'
                        ? 'Status'
                        : 'Ýagdaýy'}
                    </th>
                  </tr>
                  {paymentCardData ? (
                    <tr>
                      <td>#{paymentCardData.id}</td>
                      <td>{paymentCardData.selected_card}</td>
                      <td>{paymentCardData.created_at}</td>
                      <td
                        className={
                          paymentCardData.status !== 1
                            ? 'red'
                            : paymentCardData.status === 1
                            ? 'green'
                            : ''
                        }>
                        {paymentCardData.status === 'ugradyldy'
                          ? locale === 'TKM'
                            ? 'Ugradyldy'
                            : locale === 'РУС'
                            ? 'Отправлено'
                            : locale === 'ENG'
                            ? 'Sent'
                            : 'Ugradyldy'
                          : paymentCardData.status === 1
                          ? locale === 'TKM'
                            ? 'Kabul edildi'
                            : locale === 'РУС'
                            ? 'Принята'
                            : locale === 'ENG'
                            ? 'Accepted'
                            : 'Kabul edildi'
                          : paymentCardData.status === 0
                          ? locale === 'TKM'
                            ? 'Ret edildi'
                            : locale === 'РУС'
                            ? 'Отказано'
                            : locale === 'ENG'
                            ? 'Denied'
                            : 'Ret edildi'
                          : ''}
                      </td>
                      <td>
                        {paymentCardData.status === 'kart_chykarylmady' ? (
                          <div className="reject">
                            <div className="reason">
                              <h4>{paymentCardData.action}</h4>
                            </div>
                            <img src={allert} alt="reject" />
                          </div>
                        ) : (
                          ''
                        )}
                      </td>
                    </tr>
                  ) : (
                    <tr>
                      <td>
                        {locale === 'TKM'
                          ? 'Tabşyrlan ýüzlenme ýok'
                          : locale === 'РУС'
                          ? 'Заявок на карты нет'
                          : locale === 'ENG'
                          ? 'There are no applications for card issuance'
                          : 'Tabşyrlan ýüzlenme ýok'}
                      </td>
                      <td></td>
                      <td></td>
                      <td></td>
                      <td></td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          ) : null}
        </div>
      </div>
    </section>
  );
};

export default ImmediateCredit;
