import { FormTokenField } from '@wordpress/components';

/**
 * Multi-choice field rendered as a searchable token input (chips + type-ahead),
 * like the WordPress tags/category box. Options are { value, label }; the value
 * is an array of selected option values. Free text that doesn't match an option
 * is ignored, so only known options can be chosen.
 */
const MultiSelectField = ( { field, value, onChange } ) => {
	const options = Array.isArray( field.options ) ? field.options : [];

	const labelByValue = {};
	const valueByLabel = {};
	options.forEach( ( option ) => {
		const val = String( option.value );
		labelByValue[ val ] = option.label;
		valueByLabel[ option.label ] = val;
	} );

	const selected = Array.isArray( value ) ? value : [];
	const selectedLabels = selected
		.map( ( val ) => labelByValue[ String( val ) ] )
		.filter( Boolean );

	const handleChange = ( tokens ) => {
		const values = tokens
			.map( ( token ) =>
				typeof token === 'string'
					? valueByLabel[ token ] ?? null
					: valueByLabel[ token?.value ] ?? null
			)
			.filter( ( val ) => val !== null );
		onChange( values );
	};

	return (
		<FormTokenField
			__next40pxDefaultSize
			__nextHasNoMarginBottom
			__experimentalExpandOnFocus
			__experimentalShowHowTo={ false }
			label={ field.label }
			help={ field.help }
			placeholder={ field.placeholder }
			value={ selectedLabels }
			suggestions={ options.map( ( option ) => option.label ) }
			onChange={ handleChange }
		/>
	);
};

export default MultiSelectField;
