"use client";

import { MainButtonProps } from "@/components/ui/MainButton/MainButton";
import {
  BottomActionButton,
  BottomActionButtonProps,
} from "@/components/widgets/BottomActionButton/BottomActionButton";
import {
  SelectAnswersList,
  SelectAnswersListProps,
} from "@/components/widgets/SelectAnswersList/SelectAnswersList";
import { useDynamicSize } from "@/hooks/DOM/useDynamicSize";
import { cn } from "@/lib/utils";
import { useState } from "react";

interface QuestionSelectAnswersProps
  extends Omit<React.ComponentProps<"div">, "content"> {
  content: SelectAnswersListProps;
  bottomActionButtonProps?: BottomActionButtonProps;
}

function QuestionSelectAnswers({
  content,
  bottomActionButtonProps,
  ...props
}: QuestionSelectAnswersProps) {
  const {
    height: bottomActionButtonHeight,
    elementRef: bottomActionButtonRef,
  } = useDynamicSize<HTMLDivElement>({
    defaultHeight: 132,
  });
  const [selectedAnswers, setSelectedAnswers] = useState<
    MainButtonProps[] | null
  >(content.activeAnswers);

  const handleChangeSelectedAnswers = (answers: MainButtonProps[] | null) => {
    setSelectedAnswers(answers);
    content.onChangeSelectedAnswers?.(answers);
  };

  return (
    <div
      className="w-full"
      {...props}
      style={{
        paddingBottom: `${bottomActionButtonHeight}px`,
        ...props.style,
      }}
    >
      <SelectAnswersList
        {...content}
        onChangeSelectedAnswers={handleChangeSelectedAnswers}
      />
      {bottomActionButtonProps && (
        <BottomActionButton
          {...bottomActionButtonProps}
          className={cn("max-w-[560px]", bottomActionButtonProps.className)}
          ref={bottomActionButtonRef}
          actionButtonProps={{
            ...bottomActionButtonProps.actionButtonProps,
            disabled: selectedAnswers?.length === 0,
          }}
        />
      )}
    </div>
  );
}

export { QuestionSelectAnswers };
