/**
 * 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 { SelectControl } from '@wordpress/components';
import { GFRestAPIForm, GPEBState } from '../../../stores/gpeb';
import { __ } from '@wordpress/i18n';

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

function FormSelectControl(
	props: FormSelectControlProps & Pick< GPEBState, 'forms' >
) {
	return (
		<SelectControl
			label={ __( 'Form', 'gp-entry-blocks' ) }
			value={ props.attributes.formId ?? '' }
			hideLabelFromVision={ props.hideLabelFromVision }
			options={ [
				{ value: '', label: 'Select a Form' },
				...props.forms.map( ( form: GFRestAPIForm ) => ( {
					value: form.id,
					label: form.title,
				} ) ),
			] }
			onChange={ ( val ) => {
				props.setAttributes( {
					formId: val ? parseInt( val ) : '',
					formFields: [],
				} );
			} }
		/>
	);
}

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