import Title from "@/components/Title";
import styles from "./styles.module.scss";
import Answer from "../../components/Answer";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { sleep } from "@/services/date";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { answerTimeOut } from "../../data";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useMemo } from "react";
import { usePreloadImages } from "@/hooks/preload/images";
import { useSession } from "@/hooks/session/useSession";
import { IAnswersSessionCompatibilityV4 } from "@/api/resources/Session";
import { ESourceAuthorization } from "@/api/resources/User";

function HeadOrHeart() {
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV4);
  const { updateSession } = useSession();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { headOrHeart } = useSelector(selectors.selectCompatibilityV4Answers);
  usePreloadImages(
    ["head", "heart", "both"].map(
      (headOrHeart) => `/v4/compatibility/head-or-heart-result/${headOrHeart}.svg`
    )
  );

  const answers: { id: IAnswersSessionCompatibilityV4["head_or_heart"]; title: string }[] =
    useMemo(
      () => [
        {
          id: "heart",
          title: translate("/head-or-heart.answer1"),
        },
        {
          id: "head",
          title: translate("/head-or-heart.answer2"),
        },
        {
          id: "both",
          title: translate("/head-or-heart.answer3"),
        },
        {
          id: "depends",
          title: translate("/head-or-heart.answer4"),
        },
      ],
      [translate]
    );

  const handleClick = async (id: IAnswersSessionCompatibilityV4["head_or_heart"]) => {
    dispatch(actions.compatibilityV4Answers.update({ headOrHeart: id }));
    updateSession(
      {
        answers: {
          head_or_heart: id,
        },
      },
      ESourceAuthorization["aura.compatibility.v4"]
    );
    if (id !== headOrHeart) await sleep(answerTimeOut);
    navigate(routes.client.compatibilityV4HeadOrHeartResult());
  };

  return (
    <div className={styles.container}>
      <Title variant="h2" className={styles.title}>
        {translate("/head-or-heart.title")}
      </Title>
      {answers.map((answers, index) => (
        <Answer
          key={index}
          answer={answers}
          isSelected={headOrHeart === answers.id}
          onClick={() => handleClick(answers.id)}
        />
      ))}
    </div>
  );
}

export default HeadOrHeart;
