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 YourInclination() {
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV4);
  const { updateSession } = useSession();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { yourInclination } = useSelector(
    selectors.selectCompatibilityV4Answers
  );

  const answers: {
    id: IAnswersSessionCompatibilityV4["your_inclination"];
    title: string;
  }[] = useMemo(
    () => [
      {
        id: "fall_in_love",
        title: translate("/your-inclination.answer1"),
      },
      {
        id: "be_careful",
        title: translate("/your-inclination.answer2"),
      },
      {
        id: "look_closely",
        title: translate("/your-inclination.answer3"),
      },
    ],
    [translate]
  );

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

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

export default YourInclination;
