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 StressResponse() {
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV4);
  const { updateSession } = useSession();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { stressResponse, relationshipStatus } = useSelector(
    selectors.selectCompatibilityV4Answers
  );
  const isSingle = relationshipStatus === "single";

  const answers: {
    id: IAnswersSessionCompatibilityV4["stress_response"];
    title: string;
  }[] = useMemo(
    () => [
      {
        id: "compromise",
        title: translate(`/stress-response${isSingle ? ".single" : ""}.answer1`),
      },
      {
        id: "pause",
        title: translate(`/stress-response${isSingle ? ".single" : ""}.answer2`),
      },
      {
        id: "anger",
        title: translate(`/stress-response${isSingle ? ".single" : ""}.answer3`),
      },
      {
        id: "distance",
        title: translate(`/stress-response${isSingle ? ".single" : ""}.answer4`),
      },
    ],
    [translate]
  );

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

    return navigate(routes.client.compatibilityV4StressResponseResult());
  };

  return (
    <div className={styles.container}>
      <Title variant="h2" className={styles.title}>
        {translate(`/stress-response${isSingle ? ".single" : ""}.title`)}
      </Title>
      {answers.map((answers, index) => (
        <Answer
          key={index}
          answer={answers}
          isSelected={stressResponse === answers.id}
          onClick={() => handleClick(answers.id)}
        />
      ))}
    </div>
  );
}

export default StressResponse;
