"use client";

import React from "react";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { WebTypeComponentProps } from "@/lib/registry/types";
import { WidgetComponent, RadioTypeConfig } from "@/types/screen";

export const RadioWidget: React.FC<WebTypeComponentProps> = ({ component, value, onChange, readonly = false }) => {
  const widget = component as WidgetComponent;
  const { required } = widget;
  const config = widget.webTypeConfig as RadioTypeConfig | undefined;

  // 옵션 목록 가져오기
  const getOptions = () => {
    if (config?.options && Array.isArray(config.options)) {
      return config.options;
    }

    // 기본 옵션들
    return [
      { label: "옵션 1", value: "option1" },
      { label: "옵션 2", value: "option2" },
      { label: "옵션 3", value: "option3" },
    ];
  };

  const options = getOptions();

  // 레이아웃 방향 결정
  const isHorizontal = config?.layout === "horizontal";

  return (
    <div className="h-full w-full">
      <RadioGroup
        value={value || ""}
        onValueChange={onChange}
        disabled={readonly}
        required={required}
        className={isHorizontal ? "flex flex-row space-x-4" : "flex flex-col space-y-2"}
      >
        {options.map((option, index) => {
          const optionValue = option.value || `option_${index}`;
          return (
            <div key={optionValue} className="flex items-center space-x-2">
              <RadioGroupItem value={optionValue} id={`radio-${widget.id}-${optionValue}`} />
              <Label
                htmlFor={`radio-${widget.id}-${optionValue}`}
                className="text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                {option.label}
              </Label>
            </div>
          );
        })}
      </RadioGroup>

      {required && <div className="mt-1 text-xs text-destructive">* 필수 선택 항목입니다</div>}
    </div>
  );
};

RadioWidget.displayName = "RadioWidget";


