"use client";

import { cn } from "@/lib/utils";
import {
  MainButton,
  MainButtonProps,
} from "@/components/ui/MainButton/MainButton";
import { 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) {
  // Инициализируем состояние только один раз из activeAnswers
  const [selectedAnswers, setSelectedAnswers] = useState<
    MainButtonProps[] | null
  >(() => activeAnswers ?? null);

  const handleAnswerClick = (answer: MainButtonProps) => {
    const newSelectedAnswers = selectedAnswers?.some((a) => a.id === answer.id)
      ? selectedAnswers.filter((a) => a.id !== answer.id) || null
      : [...(selectedAnswers || []), answer];

    setSelectedAnswers(newSelectedAnswers);
    onChangeSelectedAnswers?.(newSelectedAnswers);
    onAnswerClick?.(answer);
  };

  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 };
