/**
 * Form select dropdown component to be used in inspector controls
 */

/**
 * WordPress provides React during the page load. This is for TypeScript type checking only.
 *
 * Importing React from @wordpress/element causes "Cannot read property 'createElement' of undefined"
 */
import React from 'react';

import { withSelect } from '@wordpress/data';
import { Forms } from '../stores/gpeb';
import { __ } from '@wordpress/i18n';

interface FormSelectControlProps extends BlockProps< any > {
	hideLabelFromVision?: boolean;
}

function FormSelectPlaceholder(
	props: FormSelectControlProps & { forms: Forms }
) {
	const change = ( event ) => {
		const { value } = event.target;

		props.setAttributes( {
			formId: value ? parseInt( value ) : '',
			formFields: [],
		} );
	};

	return (
		<select
			value={ props.attributes.formId }
			onBlur={ change }
			onChange={ change }
		>
			<option value="">{ __( 'Select a Form', 'gp-entry-blocks' ) }</option>
			{ props.forms.map( ( form ) => (
				<option value={ form.id } key={ form.id }>
					{ form.title }
				</option>
			) ) }
		</select>
	);
}

export default withSelect< { forms: Forms }, FormSelectControlProps >(
	( select, ownProps ) => {
		return {
			forms: select( 'gp-entry-blocks' ).getForms(),
		};
	}
)( FormSelectPlaceholder );
