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

function ResultAnalysis() {
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV4);
  const { updateSession } = useSession();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { resultAnalysis } = useSelector(
    selectors.selectCompatibilityV4Answers
  );

  const answers: {
    id: IAnswersSessionCompatibilityV4["result_analysis"];
    title: string;
  }[] = useMemo(
    () => [
      {
        id: "find_answers",
        title: translate("/result-analysis.answer1"),
      },
      {
        id: "improve_relationships",
        title: translate("/result-analysis.answer2"),
      },
      {
        id: "what_awaits",
        title: translate("/result-analysis.answer3"),
      },
      {
        id: "continue_relationship",
        title: translate("/result-analysis.answer4"),
      },
      {
        id: "just_interested",
        title: translate("/result-analysis.answer5"),
      },
    ],
    [translate]
  );

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

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

export default ResultAnalysis;
