/**
 * Number Field Component
 *
 * Renders a numeric input field with variable picker support.
 * Only shows integer variables in the picker by default.
 */

import { memo } from 'react';
import { Label } from '../ui/label';
import { VariableInput } from '../VariableInput';
import { ActionField } from '../../types/action';
import { AvailableContext } from '../../types/workflow-context';

interface NumberFieldProps {
  fieldName: string;
  field: ActionField;
  value: number | string;
  onChange: (value: number | string) => void;
  availableContext: AvailableContext;
  error?: string;
}

export const NumberField = memo(function NumberField({
  fieldName,
  field,
  value,
  onChange,
  availableContext,
  error,
}: NumberFieldProps) {
  // Get allowed variable types from field schema, default to ['integer']
  const allowedTypes = field.allowed_variable_types || ['integer'];

  return (
    <div className="space-y-2">
      <Label htmlFor={fieldName} className="text-slate-900">
        {field.label}
        {field.required && <span className="text-red-600 ml-1">*</span>}
      </Label>

      <VariableInput
        value={String(value ?? '')}
        onChange={(val) => {
          // If it contains variable syntax, keep as string
          // Otherwise, try to parse as number
          if (val.includes('{{') && val.includes('}}')) {
            onChange(val);
          } else if (val === '') {
            onChange('');
          } else {
            const parsed = Number(val);
            onChange(isNaN(parsed) ? val : parsed);
          }
        }}
        availableContext={availableContext}
        placeholder={field.placeholder || field.description}
        allowedTypes={allowedTypes}
      />

      {field.description && <p className="text-xs text-slate-500">{field.description}</p>}
      {error && <p className="text-xs text-red-600">{error}</p>}
    </div>
  );
});
