/**
 * WordPress dependencies
 */
import { cloneBlock } from '@safe-wordpress/blocks';
import { store as BLOCK_EDITOR } from '@safe-wordpress/block-editor';
import { store as NOTICES } from '@safe-wordpress/notices';
import { useDispatch, useSelect } from '@safe-wordpress/data';
import { _x, sprintf } from '@safe-wordpress/i18n';
import type { BlockInstance } from '@safe-wordpress/blocks';

/**
 * External dependencies
 */
import { map } from 'lodash';
import { getFormPatterns } from '@nelio/forms/utils';
import type { FormPattern } from '@nelio/forms/types';

/**
 * Internal dependencies
 */
import BlockPatternList from './block-pattern-list';

type FormPatternsProps = {
	readonly clientId?: string;
};
export const FormPatterns = ( {
	clientId,
}: FormPatternsProps ): JSX.Element => {
	const { createSuccessNotice } = useDispatch( NOTICES );
	const { replaceBlocks } = useDispatch( BLOCK_EDITOR );

	const clientIds = useSelect( ( select ) =>
		clientId
			? select( BLOCK_EDITOR ).getClientIdsOfDescendants( [ clientId ] )
			: map(
					select( BLOCK_EDITOR ).getBlocks(),
					( block ) => block.clientId
			  )
	);

	const onClickPattern = (
		pattern: FormPattern,
		blocks: ReadonlyArray< BlockInstance >
	) => {
		void replaceBlocks(
			clientIds,
			map( blocks, ( block ) => cloneBlock( block ) )
		);
		void createSuccessNotice(
			sprintf(
				/* translators: %s: block pattern title. */
				_x( 'Form pattern "%s" inserted.', 'text', 'nelio-forms' ),
				pattern.title
			),
			{ type: 'snackbar' }
		);
	};

	return (
		<BlockPatternList
			blockPatterns={ getFormPatterns() }
			onClickPattern={ onClickPattern }
		/>
	);
};
