import { RangeControl } from '@wordpress/components';

const parseNumber = ( value, fallback ) => {
	if ( value === undefined || value === null || value === '' ) {
		return fallback;
	}

	const parsed = Number( value );
	return Number.isFinite( parsed ) ? parsed : fallback;
};

const RangeField = ( { field, value, onChange } ) => {
	const min = Number.isFinite( field.min ) ? field.min : 0;
	const max = Number.isFinite( field.max ) ? field.max : 100;
	const step = Number.isFinite( field.step ) ? field.step : 1;
	const numericValue = parseNumber( value, field.default ?? min );

	return (
		<RangeControl
			label={ field.label }
			help={ field.help }
			min={ min }
			max={ max }
			step={ step }
			value={ numericValue }
			onChange={ ( nextValue ) =>
				onChange(
					nextValue === undefined || nextValue === null
						? null
						: Number( nextValue )
				)
			}
		/>
	);
};

export default RangeField;
