"use client";

import { cn } from "@/lib/utils";
import {
  MainButton,
  MainButtonProps,
} from "@/components/ui/MainButton/MainButton";
import { useEffect, useState, useRef } 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 isInitialMount = useRef(true);

  useEffect(() => {
    setSelectedAnswer(activeAnswer ?? null);
  }, [activeAnswer]);

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

  useEffect(() => {
    // НЕ вызываем callback при первоначальной загрузке компонента
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    
    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 };
