import { BaseControl, CheckboxControl } from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';

const CheckboxGroupField = ( { field, value, onChange } ) => {
	const selectedValues = Array.isArray( value ) ? value : [];
	const options = field.options ?? [];
	const instanceId = useInstanceId(
		CheckboxGroupField,
		'checkbox-group-field'
	);
	const controlId = field?.id ?? field?.name ?? instanceId;

	const toggleValue = ( optionValue, isChecked ) => {
		if ( isChecked ) {
			onChange( [
				...selectedValues.filter( ( item ) => item !== optionValue ),
				optionValue,
			] );
			return;
		}

		onChange( selectedValues.filter( ( item ) => item !== optionValue ) );
	};

	return (
		<BaseControl
			id={ controlId }
			label={ field.label }
			help={ field.help }
			required={ field.required }
		>
			{ options.map( ( option ) => {
				const optionValue = option.value ?? option.label;

				return (
					<CheckboxControl
						key={ optionValue }
						label={ option.label ?? option.value }
						checked={ selectedValues.includes( optionValue ) }
						onChange={ ( isChecked ) =>
							toggleValue( optionValue, isChecked )
						}
					/>
				);
			} ) }
		</BaseControl>
	);
};

export default CheckboxGroupField;
