// 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 TopupModal from "../components/topup/TopupModal";
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 topup from "../icons/topup-black.svg";
import add from "../icons/add.svg";
import allert from "../icons/info-circle.svg";

const Topup = () => {
  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 [topupData, setTopupData] = useState();
  const [progress, setProgress] = useState(0);

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

  useEffect(() => {
    let isMounted = true;
    axios
      .get(`${dataDestination}/type_account_replenishment`)
      .then((res) => {
        if (isMounted) {
          setTopupData(res.data);
        }
      })
      .catch();
    return () => {
      isMounted = false;
    };
  }, []);

  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={topup}
        link={"/home/topup"}
        linkTitle={
          locale === "TKM"
            ? "Hasaby doldurmak"
            : locale === "РУС"
            ? "Пополнение счета"
            : locale === "ENG"
            ? "Top up"
            : "Hasaby doldurmak"
        }
      />
      <TopupModal
        setModalOpen={setModalOpen}
        modalOpen={modalOpen}
        stage={stage}
        setStage={setStage}
        loader={loader}
        setLoader={setLoader}
        setSuccess={setSuccess}
        setError={setError}
        topupData={topupData}
        setProgress={setProgress}
      />
      {loader ? <ProgressLoader progress={progress} /> : null}
      <div className="container">
        <div className="cards-inner">
          <div className="card-title">
            <h2 className="cards-title">
              {locale === "TKM"
                ? "Hasaby doldurmak üçin onlaýn ýüzlenme"
                : locale === "РУС"
                ? "Онлайн-заявка для пополнения счета"
                : locale === "ENG"
                ? "Online application for balance top up"
                : "Hasaby doldurmak üç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="home-table-wrapper">
            <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>
                  <th>
                    {locale === "TKM"
                      ? "Amal"
                      : locale === "РУС"
                      ? "Действие"
                      : locale === "ENG"
                      ? "Operation"
                      : "Amal"}
                  </th>
                </tr>
                {user ? (
                  user.account_replenishment.length !== 0 ? (
                    [...user.account_replenishment].reverse().map((el, i) => {
                      return (
                        <tr key={i}>
                          <td>#{el.id}</td>
                          <td>{el.selected_type_account_replenishment}</td>
                          <td>
                            {el.created_at
                              .split(" ")[0]
                              .replace("-", ".")
                              .replace("-", ".")}
                          </td>
                          <td
                            className={
                              el.status === "hasap_chykarylmady"
                                ? "red"
                                : el.status === "hasap_chykaryldy" ||
                                  el.status === "kabul_edildi"
                                ? "green"
                                : ""
                            }
                          >
                            {el.status === "ugradyldy" ||
                            el.status === null ||
                            el.status === "null"
                              ? locale === "TKM"
                                ? "Ugradyldy"
                                : locale === "РУС"
                                ? "Отправлено"
                                : locale === "ENG"
                                ? "Sent"
                                : "Ugradyldy"
                              : el.status === "kabul_edildi"
                              ? locale === "TKM"
                                ? "Kabul edildi"
                                : locale === "РУС"
                                ? "Принята"
                                : locale === "ENG"
                                ? "Accepted"
                                : "Kabul edildi"
                              : el.status === "seredilyar"
                              ? locale === "TKM"
                                ? "Görülyar"
                                : locale === "РУС"
                                ? "На стадии рассмотрения"
                                : locale === "ENG"
                                ? "Under consideration"
                                : "Görülyar"
                              : el.status === "hasap_chykaryldy"
                              ? locale === "TKM"
                                ? "Tassyklandy"
                                : locale === "РУС"
                                ? "Утверждено"
                                : locale === "ENG"
                                ? "Approved"
                                : "Tassyklandy"
                              : el.status === "hasap_chykarylmady"
                              ? locale === "TKM"
                                ? "Ret edildi"
                                : locale === "РУС"
                                ? "Отказано"
                                : locale === "ENG"
                                ? "Denied"
                                : "Ret edildi"
                              : ""}
                          </td>
                          <td>
                            {el.status === "5" ? (
                              <div className="reject">
                                <div className="reason">
                                  <h4>{el.action}</h4>
                                </div>
                                <img src={allert} alt="reject" />
                              </div>
                            ) : (
                              ""
                            )}
                          </td>
                        </tr>
                      );
                    })
                  ) : (
                    <tr>
                      <td>
                        {locale === "TKM"
                          ? "Hasaby doldurmak üçin ýüzlenme ýok"
                          : locale === "РУС"
                          ? "Заявок на пополнение счета нет"
                          : locale === "ENG"
                          ? "There are no applications for balance top up"
                          : "Hasaby doldurmak üçin ýüzlenme ýok"}
                      </td>
                      <td></td>
                      <td></td>
                      <td></td>
                      <td></td>
                    </tr>
                  )
                ) : (
                  <tr>
                    <td>
                      {locale === "TKM"
                        ? "Hasaby doldurmak üçin ýüzlenme ýok"
                        : locale === "РУС"
                        ? "Заявок на пополнение счета нет"
                        : locale === "ENG"
                        ? "There are no applications for balance top up"
                        : "Hasaby doldurmak üçin ýüzlenme ýok"}
                    </td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </section>
  );
};

export default Topup;
