/**
 * 숫자 입력 필드 컴포넌트
 * 기존 ItemForm과 100% 동일한 디자인
 */

'use client';

import { Label } from '@/components/ui/label';
import { NumberInput } from '@/components/ui/number-input';
import type { DynamicFieldRendererProps } from '../types';

export function NumberField({
  field,
  value,
  onChange,
  error,
  disabled,
}: DynamicFieldRendererProps) {
  const fieldKey = field.field_key || `field_${field.id}`;

  // properties에서 단위, 정밀도 등 추출
  const unit = field.properties?.unit as string | undefined;
  const step = field.properties?.precision ? Math.pow(10, -field.properties.precision) : 1;

  return (
    <div>
      <Label htmlFor={fieldKey}>
        {field.field_name}
        {unit && ` (${unit})`}
        {field.is_required && <span className="text-red-500"> *</span>}
      </Label>
      <NumberInput
        id={fieldKey}
        placeholder={field.placeholder || `${field.field_name}을(를) 입력하세요`}
        value={value !== null && value !== undefined ? Number(value) : undefined}
        onChange={(newValue) => {
          // undefined이면 null, 아니면 숫자로 변환
          onChange(newValue ?? null);
        }}
        disabled={disabled}
        step={step}
        min={field.validation_rules?.min}
        max={field.validation_rules?.max}
        allowDecimal={step !== 1}
        className={error ? 'border-red-500' : ''}
      />
      {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>
  );
}