"use client";

import { cn } from "@/lib/utils";
import {
  MainButton,
  MainButtonProps,
} from "@/components/ui/MainButton/MainButton";
import { useEffect, useState } from "react";

export interface SelectAnswersListProps extends React.ComponentProps<"div"> {
  answers: MainButtonProps[];
  activeAnswers: MainButtonProps[] | null;
  onChangeSelectedAnswers?: (answers: MainButtonProps[] | null) => void;
  onAnswerClick?: (answer: MainButtonProps | null) => void;
}

function SelectAnswersList({
  className,
  answers,
  activeAnswers,
  onChangeSelectedAnswers,
  onAnswerClick,
  ...props
}: SelectAnswersListProps) {
  const [selectedAnswers, setSelectedAnswers] = useState<
    MainButtonProps[] | null
  >(activeAnswers);

  const handleAnswerClick = (answer: MainButtonProps) => {
    if (selectedAnswers?.some((a) => a.id === answer.id)) {
      setSelectedAnswers(
        (prev) => prev?.filter((a) => a.id !== answer.id) || null
      );
    } else {
      setSelectedAnswers((prev) => [...(prev || []), answer]);
    }
    onAnswerClick?.(answer);
  };

  useEffect(() => {
    onChangeSelectedAnswers?.(selectedAnswers);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedAnswers]);

  return (
    <div className={cn("flex flex-col gap-3 w-full", className)} {...props}>
      {answers.map((answer) => (
        <MainButton
          key={answer.id}
          {...answer}
          onClick={() => handleAnswerClick(answer)}
          active={selectedAnswers?.some((a) => a.id === answer.id)}
        />
      ))}
    </div>
  );
}

export { SelectAnswersList };
