import { HStack } from '../h-stack';
import { Text } from '../text';
import RangeControl from '../range-control';
import NumberControl from '../number-control';
import styles from './style.module.scss';
import type { InputWithSliderProps } from './types';
import InputControlPrefixWrapper from '../input-control/input-prefix-wrapper';

export const InputWithSlider = ( {
	min,
	max,
	label,
	abbreviation,
	onChange,
	value,
}: InputWithSliderProps ) => {
	const onNumberControlChange = ( newValue?: number | string ) => {
		if ( ! newValue ) {
			onChange( 0 );
			return;
		}
		if ( typeof newValue === 'string' ) {
			onChange( parseInt( newValue, 10 ) );
			return;
		}
		onChange( newValue );
	};

	return (
		<HStack spacing={ 4 }>
			<NumberControl
				className={ styles[ 'number-control' ] }
				min={ min }
				max={ max }
				label={ label }
				hideLabelFromVision
				value={ value }
				onChange={ onNumberControlChange }
				prefix={
					<InputControlPrefixWrapper className={ styles.prefix }>
						<Text color="inherit" lineHeight={ 1 }>
							{ abbreviation }
						</Text>
					</InputControlPrefixWrapper>
				}
				spinControls="none"
			/>
			<RangeControl
				className={ styles.range }
				label={ label }
				hideLabelFromVision
				min={ min }
				max={ max }
				value={ value }
				// @ts-expect-error `RangeControl` may call `onChange` with `undefined`, but this expects a `number`.
				// See: https://github.com/WordPress/gutenberg/pull/40535#issuecomment-1172418185
				onChange={ onChange }
				withInputField={ false }
			/>
		</HStack>
	);
};
