"use client";

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

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

function RadioAnswersList({
  className,
  answers,
  activeAnswer,
  onAnswerClick,
  onChangeSelectedAnswer,
  ...props
}: RadioAnswersListProps) {
  const [selectedAnswer, setSelectedAnswer] = useState<MainButtonProps | null>(
    activeAnswer
  );

  const handleAnswerClick = (answer: MainButtonProps) => {
    setSelectedAnswer(answer);
    onAnswerClick?.(answer);
  };

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

  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={selectedAnswer?.id === answer.id}
        />
      ))}
    </div>
  );
}

export { RadioAnswersList };
