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 { IAnswersSession } from "@/api/resources/Session";
import { ESourceAuthorization } from "@/api/resources/User";

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

  const aspects: { id: IAnswersSession["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"),
        },
      ],
      [translate]
    );

  const handleClick = async (id: IAnswersSession["what_aspects"]) => {
    dispatch(actions.palmistryV1Answers.update({ whatAspects: id }));
    await updateSession(
      {
        answers: {
          what_aspects: id,
        },
      },
      ESourceAuthorization["aura.palmistry.new"]
    );
    if (id !== whatAspects) await sleep(answerTimeOut);
    navigate(routes.client.palmistryV1RelationshipStatus());
  };

  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;
