/**
 * External dependencies.
 */
import { SelectControl } from '@wordpress/components';

/**
 * Enhanced SelectControl that supports options with children.  
 *
 * @since x.x.x  
 *  
 * @param {Object} props - All props from core SelectControl plus enhanced options.  
 * @return {Element}          - The custom select control component.  
 */  
const CustomSelectControl = ( props ) => {
	const { options = [], value, onChange, ...selectControlProps } = props;

	return (
		<SelectControl
			{ ...selectControlProps }
			value={ value }
			onChange={ onChange }
			__next40pxDefaultSize
			__nextHasNoMarginBottom
		>
			{ options.map( ( option, index ) =>
				option.options && Array.isArray( option.options ) ? (
					<optgroup key={ `group-${ index }` } label={ option.label }>
						{ option.options.map( ( childOption, childIndex ) => (
							<option
								key={ `child-${ index }-${ childIndex }` }
								value={ childOption.value }
								disabled={ childOption.disabled || false }
							>
								{ childOption.label }
							</option>
						) ) }
					</optgroup>
				) : (
					<option key={ `option-${ index }` } value={ option.value } disabled={ option.disabled || false }>
						{ option.label }
					</option>
				)
			) }
		</SelectControl>
	);
};

export default CustomSelectControl;
