/**
 * 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 { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import SummaryColumnsControl from './SummaryColumnsControl';
import { __ } from '@wordpress/i18n';
import { Spinner, Placeholder, PanelBody, TextareaControl } from '@wordpress/components';
import { useBlockAJAXPreview, usePreventInnerEventsRef } from '../../hooks';

export interface GPEntriesTableBlockAttributes {
	formFields: any[];
	noEntriesFoundMessage: string
}

/*
 * @todo Add example for styles preview: https://github.com/WordPress/gutenberg/blob/102e8b5/packages/block-library/src/table/index.js#L24-L95
 */
const Edit = ( args: BlockProps< GPEntriesTableBlockAttributes > ) => {
	const previewHTML = useBlockAJAXPreview( args );
	const preventInnerEventsRef = usePreventInnerEventsRef( previewHTML );
	const blockProps = useBlockProps( { ref: preventInnerEventsRef } );

	const inspectorControls = (
		<InspectorControls>
			{ args.context[ 'gp-entry-blocks/formId' ] && (
				<>
					<PanelBody
						className="gpeb_panel_entries_table_settings"
						title={ __( 'Settings', 'gp-entry-blocks' ) }
					>
						<SummaryColumnsControl
							{ ...args }
							label={ __( 'Summary Columns', 'gp-entry-blocks' ) }
						/>
					</PanelBody>
					<PanelBody
						className="gpeb_panel_entries_table_messages"
						title={ __( 'Messages', 'gp-entry-blocks' ) }
					>
						<TextareaControl
							value={ args.attributes.noEntriesFoundMessage }
							onChange={ ( noEntriesFoundMessage ) =>
								args.setAttributes( { noEntriesFoundMessage } )
							}
							label={ __( 'No Entries Found', 'gp-entry-blocks' ) }
						/>
					</PanelBody>
				</>
			) }
		</InspectorControls>
	);

	if ( ! previewHTML ) {
		return (
			<>
				{ inspectorControls }
				<div { ...blockProps }>
					<Placeholder>
						<Spinner />
					</Placeholder>
				</div>
			</>
		);
	}

	return (
		<>
			{ inspectorControls }
			<table { ...blockProps } dangerouslySetInnerHTML={ { __html: previewHTML } } />
		</>
	);
};

/**
 * 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,
};
