import FieldControl from '../components/FieldControl';
import ButtonGroup from '../components/ButtonGroup';
import {useEffect} from '@wordpress/element';

/**
 * Handles the button group component as a form field.
 */
const ButtonGroupField = ( {field, value, onChange} ) => {

	const isValueEmpty = value === undefined || value === null || value === '';
	useEffect( () => {
		if ( isValueEmpty && field.default !== undefined ) {
			onChange( field.id, field.default );
		}
	}, [isValueEmpty, field.default, field.id, onChange] );

	const currentValue = isValueEmpty ? field.default : value;

	return (
		<FieldControl
			label={field.label}
			help={field.description}
			id={field.id}
			className={field.depends_on ? 'adpresso-field-control__child' : undefined}
			premium={field.premium}
		>
			<ButtonGroup
				options={field.options || []}
				value={currentValue}
				onChange={( newValue ) => onChange( field.id, newValue )}
			/>
		</FieldControl>
	);
};

export default ButtonGroupField;
