import React from "react";

export function NumberField({ value, defaultValue = 0, onValueChange, min, max, step = 1, size = "default", disabled, className = "", id, ...props }) {
  const [internal, setInternal] = React.useState(defaultValue);
  const val = value !== undefined ? value : internal;
  const set = (v) => {
    let next = v;
    if (min !== undefined) next = Math.max(min, next);
    if (max !== undefined) next = Math.min(max, next);
    if (value === undefined) setInternal(next);
    if (onValueChange) onValueChange(next);
  };
  return (
    <div className={["o-numberfield", className].filter(Boolean).join(" ")} data-slot="number-field-group" data-size={size} {...props}>
      <button type="button" className="o-numberfield__btn" data-slot="number-field-decrement" aria-label="Decrease" disabled={disabled} onClick={() => set(val - step)}>
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"><path d="M5 12h14" /></svg>
      </button>
      <input id={id} className="o-numberfield__input" data-slot="number-field-input" inputMode="numeric" value={val} disabled={disabled}
        onChange={(e) => set(Number(e.target.value) || 0)} />
      <button type="button" className="o-numberfield__btn" data-slot="number-field-increment" aria-label="Increase" disabled={disabled} onClick={() => set(val + step)}>
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"><path d="M5 12h14" /><path d="M12 5v14" /></svg>
      </button>
    </div>
  );
}
