import {SelectControl, TextControl} from "@wordpress/components";
import {useState} from "react";

export default function NumberWithUnit({label, onChange, value, className}) {

	const splitValues = function (fontSize) {

		if( !fontSize ) {
			return {size: "0", unit: "px"};
		}

		const match = fontSize.match(/^(\d+)([a-z%]+)$/i);

		if (!match) {
			return {size: "16", unit: "px"};
		}
		return {
			size: match[1],
			unit: match[2]
		};
	}

	const [unit, setUnit] = useState(splitValues(value).unit);
	const [size, setSize] = useState(splitValues(value).size);



	const handleChange = (newSize, newUnit) => {
		if (onChange) {
			onChange(newSize + newUnit);
		}
	};


	return (
		<div className='fi-field-wrapper'>
			<div className='fi-field-label-wrapper'>
				<span className='fi-field-label'>{label}</span>
			</div>
			<div className={'fi-field-buttons-wrapper fi-input-with-columns fi-numberwithfields-wrapper' + ' ' + className}>
				<TextControl
					style={{flex: 3}}
					type={'number'}
					placeholder={'16'}
					value={size}
					onChange={(value) => {
						setSize(value);
						handleChange(value, unit);
					}}
				/>
				<SelectControl
					options={[
						{label: 'px', value: 'px'},
						{label: '%', value: '%'},
						{label: 'em', value: 'em'},
						{label: 'pt', value: 'pt'},
					]}
					style={{minWidth:'56px'}}
					value={unit}
					onChange={(value) => {
						setUnit(value);
						handleChange(size, value);
					}}

				/>
			</div>
		</div>
	);
}