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

const SelectField = ( {field, value, onChange, variantClass} ) => {

	// Detects if we have flat options or groups
	const selectOptions = Object.keys( field.options || {} ).map( ( key ) => {
		const item = field.options[key];

		// if 'item' is an object, it is a group (optgroup)
		if ( typeof item === 'object' && item !== null && !Array.isArray( item ) ) {
			return {
				label:   key,
				options: Object.entries( item ).map( ( [val, label] ) => ({
					value: val,
					label: label
				}) )
			};
		}

		return {
			value: key,
			label: item
		};
	} );

	// Synchronise data state
	useEffect( () => {
		if ( value === undefined && field.default !== undefined ) {
			onChange( field.id, field.default );
		}
	}, [value, field.default, field.id, onChange] );

	// Search the value, even in groups
	let selectedOption = null;
	if ( value !== undefined ) {
		// First on the flat level
		selectedOption = selectOptions.find( opt => String( opt.value ) === String( value ) );

		// If not found, search in groups
		if ( !selectedOption ) {
			for ( const group of selectOptions ) {
				if ( group.options ) {
					const foundInGroup = group.options.find( opt => String( opt.value ) === String( value ) );
					if ( foundInGroup ) {
						selectedOption = foundInGroup;
						break;
					}
				}
			}
		}
	}

	const handleSelectChange = ( selectedObject ) => {
		onChange( field.id, selectedObject.value );
	};

	return (
		<FieldControl label={field.label} help={field.description} id={field.id}>
			<Select
				options={selectOptions}
				selected={selectedOption || null}
				setSelected={handleSelectChange}
				placeholder={field.placeholder}
				variantClass={variantClass}
			/>
		</FieldControl>
	);
};

export default SelectField;
