import React from 'react';
import { Spinner, Placeholder } from '@wordpress/components';
import { useBlockAJAXPreview, usePreventInnerEventsRef } from '../hooks';

/**
 * Component for getting content of server-side rendered blocks such as gp-entry-blocks/entries-table.
 *
 * Ideally, we would use ServerSideRender, but it does not support passing the block context.
 *
 * @param  props
 */
const BlockPreview = (
	props: BlockProps< any > & { tag?: string }
) => {
	const previewHTML = useBlockAJAXPreview( props );
	const ref = usePreventInnerEventsRef( previewHTML );

	/* Do not attempt to render the block without context as the selected form and other settings won't be available (e.g. Style preview */
	if ( ! Object.keys( props.context ).length ) {
		return undefined;
	}

	if ( ! previewHTML ) {
		return (
			<Placeholder>
				<Spinner />
			</Placeholder>
		);
	}

	const Tag = props.tag ?? 'div';

	return (
		<Tag
			// @ts-ignore
			className="gpeb-block-preview"
			ref={ ref }
			dangerouslySetInnerHTML={ { __html: previewHTML } }
		/>
	);
};

export default BlockPreview;
