import { IAnswer } from "@/data";
import styles from "./styles.module.css";
import Answer from "@/components/Answer";
import { useState } from "react";
import MainButton from "@/components/MainButton";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";

interface IMultiplyAnswersProps {
  answers: IAnswer[];
}

function MultiplyAnswers({ answers }: IMultiplyAnswersProps) {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { currentlyAffecting } = useSelector(selectors.selectQuestionnaire);
  const [selectedAnswers, setSelectedAnswers] = useState<string[]>(
    currentlyAffecting?.split("$") || []
  );

  const handleClick = (answer: IAnswer) => {
    if (selectedAnswers.includes(answer.id)) {
      return setSelectedAnswers((prevState) =>
        prevState.filter((item) => item !== answer.id)
      );
    }
    if (answer.id === "none_of_these") {
      return setSelectedAnswers([answer.id]);
    }
    if (
      selectedAnswers.includes("none_of_these") &&
      answer.id !== "none_of_these"
    ) {
      return;
    }
    return setSelectedAnswers((prevState) => [...prevState, answer.id]);
  };

  const handleNext = () => {
    dispatch(
      actions.questionnaire.update({
        currentlyAffecting: selectedAnswers.join("$"),
      })
    );
    navigate(`${routes.client.questionnaire()}/relationships/partnerPriority`);
  };

  return (
    <>
      {answers.map((answer, index) => (
        <Answer
          key={index}
          answer={answer}
          disabled={
            selectedAnswers.includes("none_of_these") &&
            answer.id !== "none_of_these"
          }
          type="multiply"
          active={selectedAnswers.includes(answer.id)}
          onClick={() => handleClick(answer)}
        />
      ))}
      <MainButton
        className={styles.button}
        onClick={handleNext}
        disabled={!selectedAnswers.length}
      >
        {t("next")}
      </MainButton>
    </>
  );
}

export default MultiplyAnswers;
