/**
 * Wrapper component for the RangeControl
 * Uses debounce to optimize the performance
 * Props: see https://developer.wordpress.org/block-editor/components/range-control/
 * 				+ custom property 'unit'
 */
import {useState, useCallback} from '@wordpress/element';
import {RangeControl} from '@wordpress/components';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import './RangeControl.scss';

export default function FloRangeControl(props) {
	const b = 'flo-control-range';

	const [localValue, setLocalValue] = useState(props.value);

	const changeHandlerDeb = useCallback(_.debounce(props.onChange, 300), [
		props.onChange,
	]);

	const changeHandler = (newValue) => {
		setLocalValue(newValue);
		changeHandlerDeb(newValue);
	};
	return (
		<div
			className={classnames(b, {
				'flo-control-range--has-unit': props.unit,
			})}
		>
			<RangeControl
				{...props}
				label={props.label}
				value={localValue}
				onChange={(val) => changeHandler(val)}
				className={props.className}
				min={props.min}
				max={props.max}
				step={props.step}
			/>
			{typeof props.unit !== 'undefined' && props.unit !== '' ? (
				<span className={b + '--unit'}>{props.unit}</span>
			) : (
				<span className={b + '--unit'} />
			)}
		</div>
	);
}

FloRangeControl.propTypes = {
	label: PropTypes.string,
	className: PropTypes.string,
	help: PropTypes.string,
	options: PropTypes.array,
	onChange: PropTypes.func,
	unit: PropTypes.string,
	step: PropTypes.number,
	min: PropTypes.number,
	max: PropTypes.number,
	value: PropTypes.number,
};

FloRangeControl.defaultProps = {
	value: 1,
	className: '',
	help: '',
	settings: {
		step: 1,
		min: 1,
		max: 12,
		unit: '',
	},
	onChange: (val) => {
		console.log('Control should have a changeHandler. Value:', val);
	},
};
