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

function WhoMatter() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { updateSession } = useSession();
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV2);
  const { whoMatter } = useSelector(selectors.selectCompatibilityV2Answers);

  const answers: {
    id: IAnswersSessionCompatibilityV2["who_matter"];
    title: string;
  }[] = useMemo(
    () => [
      {
        id: "me",
        title: translate("/who-matter.answer1"),
      },
      {
        id: "kids",
        title: translate("/who-matter.answer2"),
      },
      {
        id: "family",
        title: translate("/who-matter.answer3"),
      },
    ],
    [translate]
  );

  const handleClick = async (
    id: IAnswersSessionCompatibilityV2["who_matter"]
  ) => {
    dispatch(actions.compatibilityV2Answers.update({ whoMatter: id }));
    updateSession(
      {
        answers: {
          who_matter: id,
        },
      },
      ESourceAuthorization["aura.compatibility.v2"]
    );
    if (id !== whoMatter) await sleep(answerTimeOut);
    navigate(routes.client.compatibilityV2YourPriority());
  };

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

export default WhoMatter;
