import { useTranslations } from "@/hooks/translations";
import Title from "@/components/Title";
import styles from "./styles.module.css";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { useCallback, useEffect, useRef, useState } from "react";
import { AIRequestsV2, useApi, useApiCall } from "@/api";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import FullScreenModal from "@/components/FullScreenModal";
import ProgressBarsModal, { ProgressBar } from "@/components/ProgressBarsModal";
import {
  getCategoryIdByZodiacSign,
  getZodiacSignByDate,
} from "@/services/zodiac-sign";
import { getRandomArbitrary } from "@/services/random-value";

function EnergyVampirismResult(): JSX.Element {
  const token = useSelector(selectors.selectToken);
  const { i18n, translate } = useTranslations();
  const locale = i18n.language;
  const navigate = useNavigate();
  const api = useApi();
  const homeConfig = useSelector(selectors.selectHome);
  const showNavbarFooter = homeConfig.isShowNavbar;
  const [text, setText] = useState("Loading...");
  const [isOpenModal, setIsOpenModal] = useState(true);
  const [isVisualLoading, setIsVisualLoading] = useState(true);
  const [isDataLoading, setIsDataLoading] = useState(true);
  const name = useSelector(selectors.selectUser).username;
  const birthDate = useSelector(selectors.selectBirthdate);
  const zodiacSign = getZodiacSignByDate(birthDate);
  const [backgroundUrl, setBackgroundUrl] = useState("");
  const timeoutRef = useRef<NodeJS.Timeout>();

  const progressBars: ProgressBar[] = [
    {
      label: translate("au.energy_vampirism.loading1"),
    },
    {
      label: translate("au.energy_vampirism.loading2"),
    },
    {
      label: translate("au.energy_vampirism.loading3"),
    },
    {
      label: translate("au.energy_vampirism.loading4"),
    },
  ];

  useEffect(() => {
    return () => {
      clearTimeout(timeoutRef.current);
    };
  }, []);

  const handleNext = () => {
    return navigate(routes.client.home());
  };

  const loadData = useCallback(async () => {
    const payload: AIRequestsV2.Payload = {
      aiRequest: {
        birthDate,
        sign: getZodiacSignByDate(birthDate).toLowerCase(),
      },
      promptKey: "energy_vampirism",
      token,
    };
    const aIRequest = await api.AIRequestsV2(payload);
    if (aIRequest.ai_request.state !== "ready") {
      const getAIRequest = async () => {
        const aIRequestById = await api.getAIRequestsV2({
          id: aIRequest.ai_request.id,
          token,
        });
        if (aIRequestById.ai_request.state !== "ready") {
          timeoutRef.current = setTimeout(getAIRequest, 3000);
        }
        setText(aIRequestById?.ai_request?.response?.body || "Loading...");
        setIsDataLoading(false);
        checkLoading();
        return aIRequestById.ai_request;
      };
      return await getAIRequest();
    }
    setIsDataLoading(false);
    checkLoading();
    setText(aIRequest?.ai_request?.response?.response?.body || "Loading...");

    return aIRequest?.ai_request?.response;
  }, [api, token, birthDate]);

  useApiCall<AIRequestsV2.IAIRequest>(loadData);

  useEffect(() => {
    (async () => {
      try {
        const { asset_categories } = await api.getAssetCategories({ locale });
        const categoryId = getCategoryIdByZodiacSign(
          zodiacSign,
          asset_categories
        );
        const assets = (
          await api.getAssets({ category: String(categoryId || "1") })
        ).assets;
        const randomAsset = assets[getRandomArbitrary(0, assets.length - 1)];
        setBackgroundUrl(randomAsset.url);
      } catch (error) {
        console.error("Error: ", error);
      }
    })();
  }, [api, locale, zodiacSign]);

  const getPaddingBottomPage = () => {
    if (showNavbarFooter) return "164px";
    return "108px";
  };

  function checkLoading() {
    if (isVisualLoading || isDataLoading) {
      setIsOpenModal(true);
    } else {
      setIsOpenModal(false);
    }
  }

  return (
    <section
      className={`${styles.page} page`}
      style={{ paddingBottom: getPaddingBottomPage() }}
    >
      <FullScreenModal isOpen={isOpenModal}>
        <ProgressBarsModal
          progressBars={progressBars}
          onEndLoading={() => {
            setIsVisualLoading(false);
            checkLoading();
          }}
        >
          <Title variant="h2">
            {translate("au.energy_vampirism.loading_title")}{" "}
            <span className={styles["loading-name"]}>{name}</span>
          </Title>
          <></>
        </ProgressBarsModal>
      </FullScreenModal>
      <div className={styles["cross-container"]}>
        <div className={styles.cross} onClick={handleNext}></div>
      </div>
      <div
        className={styles["sign-image"]}
        style={{ backgroundImage: `url(${backgroundUrl})` }}
      >
        <Title variant="h2">
          <span className={styles["loading-name"]}>{name}</span>{" "}
          {translate("au.energy_vampirism.result_title")}
        </Title>
      </div>
      <p className={styles.text}>{text}</p>
    </section>
  );
}

export default EnergyVampirismResult;
