import { useDispatch, useSelector } from "react-redux";
import { IAnswer } from "../../data";
import MultiplyAnswer, { TMultiplyAnswer } from "../MultiplyAnswer";
import styles from "./styles.module.scss";
import { actions, selectors } from "@/store";

interface IAnswersProps {
  answers: TMultiplyAnswer[];
  classNameAnswer?: string;
  activeAnswer?: string;
}

function MultiplyAnswers({ answers, classNameAnswer = "" }: IAnswersProps) {
  const dispatch = useDispatch();
  const storeAnswers = useSelector(selectors.selectAnswers);

  const handleClickAll = (answer: IAnswer, storeAnswer: string[]) => {
    if (storeAnswer?.length === answers.length) {
      return dispatch(
        actions.chats.updateAnswers({
          [answer.questionId]: [],
        })
      );
    }
    return dispatch(
      actions.chats.updateAnswers({
        [answer.questionId]: answers.map((item) => item.value),
      })
    );
  };

  const handleClick = (answer: IAnswer) => {
    const storeAnswer = (storeAnswers?.[
      answer.questionId as keyof typeof storeAnswers
    ] || []) as string[];

    if (answer.value === "all") {
      return handleClickAll(answer, storeAnswer);
    }

    if (storeAnswer?.includes(answer.value)) {
      dispatch(
        actions.chats.updateAnswers({
          [answer.questionId]: storeAnswer?.filter(
            (item) => item !== answer.value && item !== "all"
          ),
        })
      );
    } else {
      dispatch(
        actions.chats.updateAnswers({
          [answer.questionId]: [...storeAnswer, answer.value],
        })
      );
    }
  };

  return (
    <div className={styles.container}>
      <ul className={styles.list}>
        {answers.map((answer, index) => (
          <li className={styles.item} key={index}>
            <MultiplyAnswer
              classNameContainer={classNameAnswer}
              answer={answer}
              onClick={handleClick}
              active={storeAnswers?.[
                answer.questionId as keyof typeof storeAnswers
              ]?.includes(answer.value)}
            />
          </li>
        ))}
      </ul>
    </div>
  );
}

export default MultiplyAnswers;
