/*
 * Decimal Number Input Component
 */

import { useState, useEffect } from '@wordpress/element';

const NumberInput = ( { value, onChange, min = 0, className = '', style = {} } ) => {
	const [ inputValue, setInputValue ] = useState( value );

	// Sync local state with the prop value when it changes
	useEffect( () => {
		setInputValue( value );
	}, [ value ] );

	const handleInputChange = ( e ) => {
		let inputValue = e.target.value;

		// Determine if negative numbers are allowed
		const allowNegative = min < 0;

		// Remove leading zeros and disallow negative sign if min >= 0
		if ( !allowNegative ) {
			// Remove minus sign and leading zeros for non-negative integers
			inputValue = inputValue.replace( /^-/, '' ).replace( /^0+(?!$)/, '' );
		} else {
			// Allow negative numbers, but remove leading zeros while preserving a single '-'
			inputValue = inputValue.replace( /^(-?)0+(?!$)/, '$1' );
		}

		// Parse to integer
		let parsedValue = parseInt( inputValue, 10 );

		// If not a valid number, set to 0
		if ( isNaN( parsedValue ) ) {
			parsedValue = 0;
		}

		// Update the input field to reflect the corrected value
		e.target.value = parsedValue;

		// Update local state
		setInputValue( parsedValue );

		// Call the onChange callback
		onChange( parsedValue );
	};

	return (
		<input
			type = "number"
			value = { inputValue }
			onChange = { handleInputChange }
			min = { min < 0 ? undefined : min } // Unrestricted when negative is allowed
			className = { className }
			style = { style }
		/>
	);
};

export default NumberInput;
