import { useTranslation } from "react-i18next";
import Title from "@/components/Title";
import styles from "./styles.module.css";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { useCallback, useEffect, useState } from "react";
import { AIRequestsV2, useApi, useApiCall } from "@/api";
import { useNavigate, useSearchParams } 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 ThermalResult(): JSX.Element {
  const token = useSelector(selectors.selectToken);
  const { i18n, t } = useTranslation();
  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 [searchParams] = useSearchParams();
  const name = searchParams.get("name");
  const birthDate = searchParams.get("birthDate") || "";
  const zodiacSign = getZodiacSignByDate(birthDate);
  const [backgroundUrl, setBackgroundUrl] = useState("");

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

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

  const loadData = useCallback(async () => {
    const payload: AIRequestsV2.Payload = {
      aiRequest: {
        birthDate,
        sign: getZodiacSignByDate(birthDate).toLowerCase(),
        period: 'today'
      },
      promptKey: "compatibility_thermal",
      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") {
          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">
            {t("au.thermal_compatibility.loading_title")}
          </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})` }}
      >
        <img className={styles["thermal-image"]} src={backgroundUrl} alt="background image" />
        <Title className={styles.title} variant="h2">
          {t("au.thermal_compatibility.result_title")}{" "}
          <span className={styles["loading-name"]}>{name}</span>
        </Title>
      </div>
      <p className={styles.text}>{text}</p>
    </section>
  );
}

export default ThermalResult;
