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 { ELocalesPlacement } from "@/locales";
import { useTranslations } from "@/hooks/translations";
import { useMemo } from "react";
import { ELottieKeys, useLottie } from "@/hooks/lottie/useLottie";
import { useSession } from "@/hooks/session/useSession";
import { IAnswersSessionCompatibilityV4 } from "@/api/resources/Session";
import { ESourceAuthorization } from "@/api/resources/User";

function WhatAspects() {
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV4);
  const { updateSession } = useSession();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { whatAspects } = useSelector(selectors.selectCompatibilityV4Answers);
  useLottie({
    preloadKey: ELottieKeys.scalesHeartPalmistry,
  });

  const aspects: { id: IAnswersSessionCompatibilityV4["what_aspects"]; title: string }[] =
    useMemo(
      () => [
        {
          id: "love_relationships",
          title: translate("/what-aspects.answer1"),
        },
        {
          id: "health_vitality",
          title: translate("/what-aspects.answer2"),
        },
        {
          id: "career_destiny",
          title: translate("/what-aspects.answer3"),
        },
        {
          id: "life_transitions",
          title: translate("/what-aspects.answer4"),
        },
      ],
      [translate]
    );

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

  return (
    <div className={styles.container}>
      <Title variant="h2" className={styles.title}>
        {translate("/what-aspects.title")}
      </Title>
      {aspects.map((aspect, index) => (
        <Answer
          key={index}
          answer={aspect}
          isSelected={whatAspects === aspect.id}
          onClick={() => handleClick(aspect.id)}
        />
      ))}
    </div>
  );
}

export default WhatAspects;
