import {TextareaControl} from '@wordpress/components';
import PropTypes from 'prop-types';
import {useState, useCallback} from '@wordpress/element';

import './TextareaControl.scss';

export default function FloTextareaControl(props) {
	const b = 'flo-textarea-control';

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

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

	const changeHandler = (newValue) => {
		setLocalValue(newValue);
		changeHandlerDeb(newValue);
	};

	return (
		<div
			className={`${b} ${b}__location--${props.isSidebar ? 'main' : 'sidebar'}`}
		>
			<TextareaControl
				{...props}
				label={props.label}
				value={localValue}
				onChange={(val) => changeHandler(val)}
			/>
		</div>
	);
}

FloTextareaControl.propTypes = {
	label: PropTypes.string,
	value: PropTypes.string,
	onChange: PropTypes.func,
	debounceTime: PropTypes.number,
	isSidebar: PropTypes.bool,
};

FloTextareaControl.defaultProps = {
	label: '',
	value: '',
	onChange: (val) => {
		console.log('Control should have a changeHandler! Value:', val);
	},
	debounceTime: 300,
	isSidebar: false,
};
