import { useTranslations } from "@/hooks/translations";
import Title from "../Title";
import styles from "./styles.module.css";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useCallback, useEffect, useRef, useState } from "react";
import { AICompats, AIRequests, useApi, useApiCall } from "@/api";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { EPathsFromHome } from "@/store/siteConfig";
import FullScreenModal from "../FullScreenModal";
import CompatibilityLoading from "../CompatibilityLoading";

function CompatResultPage(): JSX.Element {
  const token = useSelector(selectors.selectToken);
  const { translate } = useTranslations();
  const navigate = useNavigate();
  const api = useApi();
  const dispatch = useDispatch();
  const birthdate = useSelector(selectors.selectBirthdate);
  const rightUser = useSelector(selectors.selectRightUser);
  const categoryId = useSelector(selectors.selectCategoryId);
  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 queryTimeOutRef = useRef<NodeJS.Timeout>();

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

  const handleNext = () => {
    if (homeConfig.pathFromHome === EPathsFromHome.breath) {
      dispatch(
        actions.siteConfig.update({
          home: { pathFromHome: homeConfig.pathFromHome, isShowNavbar: true },
        })
      );
      return navigate(routes.client.home());
    }
    if (homeConfig.pathFromHome === EPathsFromHome.compatibility) {
      return navigate(routes.client.breath());
    }
    return navigate(routes.client.compatibility());
  };

  const loadData = useCallback(async () => {
    const right_bday =
      typeof rightUser.birthDate === "string"
        ? rightUser.birthDate
        : `${rightUser.birthDate.year}-${rightUser.birthDate.month}-${rightUser.birthDate.day}`;
    const data: AICompats.Payload = {
      data: {
        left_name: "I am",
        left_bday: birthdate,
        right_name: rightUser.name,
        right_bday,
        category_id: categoryId,
      },
      token,
    };
    const aICompat = await api.getAiCompat(data);
    if (aICompat.compat.body_pending) {
      const loadAIRequest = async () => {
        const id = aICompat.compat.body_check_path.split("/")[5].split(".")[0];
        const url = `/api/v2/ai/requests/${id}.json`;
        const aIRequest = await api.getAiRequest({
          body_check_path: url,
          token,
        });
        if (aIRequest.ai_request.state !== "ready") {
          queryTimeOutRef.current = setTimeout(loadAIRequest, 3000);
        }
        setText(aIRequest?.ai_request?.response?.body || "Loading...");
        setIsDataLoading(false);
        checkLoading();
        return aIRequest.ai_request;
      };
      return await loadAIRequest();
    }
    setIsDataLoading(false);
    checkLoading();
    setText(aICompat?.compat?.body || "Loading...");

    return aICompat.compat;
  }, [api, rightUser, categoryId, birthdate, token]);

  useApiCall<AICompats.ICompat | AIRequests.IAiRequest>(loadData);

  const getPaddingBottomPage = () => {
    if (
      homeConfig.pathFromHome === EPathsFromHome.compatibility &&
      showNavbarFooter
    )
      return "246px";
    if (showNavbarFooter) return "164px";
    if (homeConfig.pathFromHome === EPathsFromHome.compatibility)
      return "174px";
    return "108px";
  };

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

  return (
    <section
      className={`${styles.page} page`}
      style={{ paddingBottom: getPaddingBottomPage() }}
    >
      <FullScreenModal isOpen={isOpenModal}>
        <CompatibilityLoading
          secondPerson={rightUser.name}
          onEndLoading={() => {
            setIsVisualLoading(false);
            checkLoading();
          }}
        />
      </FullScreenModal>
      <div className={styles.cross} onClick={handleNext}></div>
      <div className={styles["title-container"]}>
        <Title variant="h2">{translate("you_and", { user: rightUser.name })}</Title>
      </div>
      <div className={styles["result-container"]}>
        <Title variant="h3" className={styles["result-container__title"]}>
          {translate("sign")}
        </Title>
        <p className={styles["result-container__text"]}>{text}</p>
      </div>
      {text !== "Loading..." &&
        homeConfig.pathFromHome === EPathsFromHome.compatibility && (
          <div
            className={styles["button-container"]}
            style={{ bottom: showNavbarFooter ? "72px" : "0" }}
          >
            <p className={styles["button-container__text"]}>
              {translate("now-you-know")}
            </p>
            <button
              className={styles["button-container__button"]}
              onClick={handleNext}
            >
              {translate("go-through")}
            </button>
          </div>
        )}
      {text !== "Loading..." &&
        homeConfig.pathFromHome === EPathsFromHome.breath && (
          <button
            className={styles["button-green"]}
            onClick={handleNext}
            style={{ bottom: showNavbarFooter ? "88px" : "24px" }}
          >
            {translate("use-all-power")}
          </button>
        )}
    </section>
  );
}

export default CompatResultPage;
