import type { ComponentChildren } from 'preact';
import { Field } from '../core/Field';
import { Input, type InputProps } from '../core/Input';

export type NumberFieldProps = Omit<InputProps, 'type' | 'value' | 'onInput'> & {
  label?: string;
  hint?: string;
  right?: ComponentChildren;
  value?: string | number | null;
  fieldClassName?: string;
  inputClassName?: string;
  emptyValue?: number | undefined;
  onValueChange?: (value: number | undefined, raw: string) => void;
};

export function parseNumberFieldValue(raw: string, emptyValue?: number): number | undefined {
  if (raw === '') return emptyValue;
  const next = Number(raw);
  return Number.isFinite(next) ? next : emptyValue;
}

export function NumberField({
  label,
  hint,
  right,
  value,
  fieldClassName,
  inputClassName,
  emptyValue,
  onValueChange,
  required,
  compact,
  'aria-label': ariaLabel,
  ...props
}: NumberFieldProps) {
  return (
    <Field
      label={label}
      hint={hint}
      right={right as any}
      required={Boolean(required)}
      className={fieldClassName}
      compact={compact}
    >
      <Input
        {...props}
        aria-label={ariaLabel ?? label}
        required={required}
        aria-required={required ? true : undefined}
        compact={compact}
        type="number"
        value={value ?? ''}
        className={inputClassName}
        onInput={(event: any) => {
          const raw = String(event?.currentTarget?.value ?? '');
          onValueChange?.(parseNumberFieldValue(raw, emptyValue), raw);
        }}
      />
    </Field>
  );
}
