import * as React from 'react';
import Input, { baseClassName } from './index';
import join from '../utils/join';
/**
 * This component allows - and empty values as intermediery values
 * it calls change only with valid numeric values
 */
export const NumberInput = React.forwardRef((props, ref) => {
    const [value, setValue] = React.useState(() => {
        // awlays controlled
        return props.value ?? '';
    });
    const handleChange = React.useCallback((event) => {
        const { value } = event.target;
        let newVal = Number(value);
        if (value === '-' || value === '') {
            // we are saving invalid values so we allow values as empty string and '-'
            // there is a validation that prevents the
            newVal = value;
            // the value may be empty or negative
            setValue(value);
        }
        else if (!isNaN(newVal)) {
            setValue(value);
            // only set when a valid numer
            props.onChange(newVal);
        }
    }, []);
    React.useEffect(() => {
        setValue(props.value);
    }, [props.value]);
    const handleBlur = React.useCallback((event) => {
        props?.onBlur?.(event);
        // show the prop value
        if (value !== props.value) {
            setValue(props.value);
        }
    }, [props.value, value]);
    const { noArrows, ...restOfProps } = props;
    return (React.createElement(Input, { ...restOfProps, ref: ref, className: join(noArrows ? `${baseClassName}--no-arrows` : '', props.className), value: value, onBlur: handleBlur, onChange: handleChange }));
});
