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

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

  const answers: {
    id: IAnswersSessionPalmistry["relationship_status"];
    title: string;
  }[] = useMemo(
    () => [
      {
        id: "single",
        title: translate("/relationship-status.answer1"),
      },
      {
        id: "in_relationship",
        title: translate("/relationship-status.answer2"),
      },
    ],
    [translate]
  );

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

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

export default RelationshipStatus;
