import { useTranslation } from "react-i18next";
import Title from "../Title";
import styles from "./styles.module.css";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useCallback, useEffect, 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 =
    "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIzNjEyLCJpYXQiOjE2OTM0MTg5MTAsImV4cCI6MTcwMjA1ODkxMCwianRpIjoiNzg5MjkwYWItODg0YS00MGUyLTkyNjEtOWI2OGEyNjkwNmE0IiwiZW1haWwiOiJvdGhlckBleGFtcGxlLmNvbSIsInN0YXRlIjoicHJvdmVuIiwibG9jIjoiZW4iLCJ0eiI6LTI4ODAwLCJ0eXBlIjoiZW1haWwiLCJpc3MiOiJjb20ubGlmZS5hdXJhIn0.J2ocWIv5jKzuKMcwMgWMiNMyGg5qLlMAeln-bQm_9lw";
  const { t } = useTranslation();
  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 [text, setText] = useState("Loading...");
  const [isOpenModal, setIsOpenModal] = useState(true);
  
  useEffect(() => {
    const timeOut = setTimeout(() => {
      setIsOpenModal(false)
    }, 5000)
  
    return () => {
      clearTimeout(timeOut)
    }
  }, [])
  

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

  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 aIRequest = await api.getAiRequest({
          body_check_path: aICompat.compat.body_check_path,
          token,
        });
        if (aIRequest.ai_request.state !== "ready") {
          setTimeout(loadAIRequest, 3000);
        }
        setText(aIRequest?.ai_request?.response?.body || "Loading...");
        return aIRequest.ai_request;
      };
      return await loadAIRequest();
    }
    setText(aICompat?.compat?.body || "Loading...");

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

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

  return (
    <section className={`${styles.page} page`}>
      <FullScreenModal isOpen={isOpenModal}>
        <CompatibilityLoading />
      </FullScreenModal>
      {text !== "Loading..." && (
        <div className={styles.cross} onClick={handleNext}></div>
      )}
      <div className={styles["title-container"]}>
        <Title variant="h2">{t("you_and", { user: rightUser.name })}</Title>
      </div>
      <div className={styles["result-container"]}>
        <Title variant="h3" className={styles["result-container__title"]}>
          {t("sign")}
        </Title>
        <p className={styles["result-container__text"]}>{text}</p>
      </div>
      {text !== "Loading..." &&
        homeConfig.pathFromHome === EPathsFromHome.compatibility && (
          <div className={styles["button-container"]}>
            <p className={styles["button-container__text"]}>
              {t("now-you-know")}
            </p>
            <button
              className={styles["button-container__button"]}
              onClick={handleNext}
            >
              {t("go-through")}
            </button>
          </div>
        )}
      {text !== "Loading..." &&
        homeConfig.pathFromHome === EPathsFromHome.breath && (
          <button className={styles["button-green"]} onClick={handleNext}>
            {t("use-all-power")}
          </button>
        )}
    </section>
  );
}

export default CompatResultPage;
