/**
 * 라디오 버튼 그룹 필드
 * 수평/수직 레이아웃 지원
 *
 * properties: { layout: "horizontal" | "vertical" }
 * options: [{label, value}]
 */

'use client';

import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import type { DynamicFieldRendererProps } from '../types';

// 옵션을 {label, value} 형태로 정규화
function normalizeOptions(rawOptions: unknown): Array<{ label: string; value: string }> {
  if (!rawOptions) return [];

  if (typeof rawOptions === 'string') {
    return rawOptions.split(',').map(o => {
      const trimmed = o.trim();
      return { label: trimmed, value: trimmed };
    });
  }

  if (Array.isArray(rawOptions)) {
    return rawOptions.map(item => {
      if (typeof item === 'object' && item !== null && 'value' in item) {
        return {
          label: String(item.label || item.value),
          value: String(item.value),
        };
      }
      const str = String(item);
      return { label: str, value: str };
    });
  }

  return [];
}

export function RadioField({
  field,
  value,
  onChange,
  error,
  disabled,
}: DynamicFieldRendererProps) {
  const fieldKey = field.field_key || `field_${field.id}`;
  const layout = (field.properties?.layout as string) || 'vertical';
  const options = normalizeOptions(field.options);
  const stringValue = value !== null && value !== undefined ? String(value) : '';

  return (
    <div>
      <Label>
        {field.field_name}
        {field.is_required && <span className="text-red-500"> *</span>}
      </Label>
      <RadioGroup
        value={stringValue}
        onValueChange={onChange}
        disabled={disabled}
        className={`mt-2 ${layout === 'horizontal' ? 'flex flex-wrap gap-4' : 'grid gap-2'}`}
      >
        {options.map((option) => (
          <div key={option.value} className="flex items-center gap-2">
            <RadioGroupItem
              value={option.value}
              id={`${fieldKey}-${option.value}`}
            />
            <Label
              htmlFor={`${fieldKey}-${option.value}`}
              className="font-normal cursor-pointer"
            >
              {option.label}
            </Label>
          </div>
        ))}
      </RadioGroup>
      {error && (
        <p className="text-xs text-red-500 mt-1">{error}</p>
      )}
      {!error && field.description && (
        <p className="text-xs text-muted-foreground mt-1">
          * {field.description}
        </p>
      )}
    </div>
  );
}
