/**
 * 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 ServerSideRender from '@wordpress/server-side-render';
import { Spinner } from '@wordpress/components';
import { useBlockProps } from '@wordpress/block-editor';
import EditFormInspectorControls from './inspector-controls';

export interface EditFormAttributes {
	confirmationMessage: string;
}

const EditFormPlaceholder = (
	props: BlockProps< EditFormAttributes > & { forms: Forms }
) => {
	const blockProps = useBlockProps();
	const { forms, context } = props;

	if ( forms ) {
		const currentForm = forms.find(
			( form ) =>
				parseInt( form.id ) ===
				parseInt( context[ 'gp-entry-blocks/formId' ] )
		);

		if ( currentForm ) {
			return (
				<div { ...blockProps }>
					<EditFormInspectorControls { ...props } />
					<ServerSideRender
						key="form_preview"
						block="gravityforms/form"
						attributes={ {
							formId: currentForm.id,
							title: false,
							description: false,
						} }
					/>
				</div>
			);
		}
	}

	return (
		<div { ...blockProps }>
			<EditFormInspectorControls { ...props } />
			<Spinner />
		</div>
	);
};

const Edit = withSelect< { forms: Forms } >( ( select, ownProps ) => {
	return {
		forms: select( 'gp-entry-blocks' ).getForms(),
	};
} )( EditFormPlaceholder );

/**
 * Blocks with dynamic PHP backends require that we only serialize the attributes.
 *
 * @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/
 */
const Save = () => {
	return null;
};

export const settings = {
	edit: Edit,
	save: Save,
};
