import { v4 as createId } from 'uuid';
import { __ } from '@wordpress/i18n';
import { formatListNumbered as icon } from '@wordpress/icons';
import { insertObject } from '@wordpress/rich-text';
import {
	RichTextToolbarButton,
	store as blockEditorStore,
	privateApis,
} from '@wordpress/block-editor';
import { useSelect, useDispatch, useRegistry } from '@wordpress/data';
import { store as coreDataStore } from '@wordpress/core-data';
import { createBlock, store as blocksStore } from '@wordpress/blocks';
import { unlock } from '../lock-unlock';
import { name as FOOTNOTES_BLOCK_NAME } from './';

export const formatName = 'core/footnote';

const { usesContextKey } = unlock( privateApis );
const POST_CONTENT_BLOCK_NAME = 'core/post-content';
const SYNCED_PATTERN_BLOCK_NAME = 'core/block';

/**
 * Finds the first footnotes block in the post content, searching breadth
 * first. Inner blocks of synced patterns are not searched.
 *
 * @param {Function} getBlocks             The block editor's `getBlocks` selector.
 * @param {string}   [postContentClientId] Client ID of the post content block, if
 *                                         there is one.
 * @return {?Object} The footnotes block, or `null` if there is none.
 */
function findFootnotesBlock( getBlocks, postContentClientId ) {
	// When called with a post content block, getBlocks will return
	// the block with controlled inner blocks included.
	const queue = [ ...getBlocks( postContentClientId ) ];
	while ( queue.length ) {
		const block = queue.shift();
		if ( block.name === FOOTNOTES_BLOCK_NAME ) {
			return block;
		}
		queue.push( ...block.innerBlocks );
	}
	return null;
}

export const format = {
	title: __( 'Footnote' ),
	tagName: 'sup',
	className: 'fn',
	attributes: {
		'data-fn': 'data-fn',
	},
	interactive: true,
	contentEditable: false,
	[ usesContextKey ]: [ 'postType', 'postId' ],
	edit: function Edit( {
		value,
		onChange,
		isObjectActive,
		context: { postType, postId },
	} ) {
		const registry = useRegistry();
		const {
			getSelectedBlockClientId,
			getBlocks,
			getBlockRootClientId,
			getBlockName,
			getBlockParentsByBlockName,
		} = registry.select( blockEditorStore );
		const isFootnotesSupported = useSelect(
			( select ) => {
				if (
					! select( blocksStore ).getBlockType( 'core/footnotes' )
				) {
					return false;
				}

				const allowedBlocks =
					select( blockEditorStore ).getSettings().allowedBlockTypes;
				if (
					allowedBlocks === false ||
					( Array.isArray( allowedBlocks ) &&
						! allowedBlocks.includes( 'core/footnotes' ) )
				) {
					return false;
				}

				const entityRecord = select( coreDataStore ).getEntityRecord(
					'postType',
					postType,
					postId
				);

				if ( 'string' !== typeof entityRecord?.meta?.footnotes ) {
					return false;
				}

				// Checks if the selected block lives within a pattern.
				const {
					getBlockParentsByBlockName: _getBlockParentsByBlockName,
					getSelectedBlockClientId: _getSelectedBlockClientId,
					getBlockName: _getBlockName,
					getBlocks: _getBlocks,
					canInsertBlockType: _canInsertBlockType,
				} = select( blockEditorStore );

				const selectedClientId = _getSelectedBlockClientId();

				if ( ! selectedClientId ) {
					return false;
				}

				// Check if the selected block itself is a footnotes block.
				if (
					_getBlockName( selectedClientId ) === FOOTNOTES_BLOCK_NAME
				) {
					return false;
				}

				// When the post has no footnotes block, adding a footnote inserts
				// one. Don't offer it when that isn't possible, such as in a post
				// type with a locked template.
				const parentPostContent = _getBlockParentsByBlockName(
					selectedClientId,
					POST_CONTENT_BLOCK_NAME
				);
				const rootClientId = parentPostContent.length
					? parentPostContent[ parentPostContent.length - 1 ]
					: null;
				if (
					! _canInsertBlockType(
						FOOTNOTES_BLOCK_NAME,
						rootClientId
					) &&
					! findFootnotesBlock( _getBlocks, parentPostContent[ 0 ] )
				) {
					return false;
				}

				const parentCoreBlocks = _getBlockParentsByBlockName(
					selectedClientId,
					SYNCED_PATTERN_BLOCK_NAME
				);
				return ! parentCoreBlocks || parentCoreBlocks.length === 0;
			},
			[ postType, postId ]
		);

		const { selectionChange, insertBlock } =
			useDispatch( blockEditorStore );

		if ( ! isFootnotesSupported ) {
			return null;
		}

		function onClick() {
			registry.batch( () => {
				let id;
				if ( isObjectActive ) {
					const object = value.replacements[ value.start ];
					id = object?.attributes?.[ 'data-fn' ];
				} else {
					// The ID doubles as the anchor target of the footnote link.
					// A CSS identifier cannot start with a digit, so a bare UUID
					// (which often does) breaks `querySelector( '#' + id )` and
					// `#id` style rules on the front end. Prefix it with a letter.
					id = `fn-${ createId() }`;
					const newValue = insertObject(
						value,
						{
							type: formatName,
							attributes: {
								'data-fn': id,
							},
							innerHTML: `<a href="#${ id }" id="${ id }-link">*</a>`,
						},
						value.end,
						value.end
					);
					newValue.start = newValue.end - 1;
					onChange( newValue );
				}

				const selectedClientId = getSelectedBlockClientId();

				/*
				 * Attempts to find a common parent post content block.
				 * This allows for locating blocks within a page edited in the site editor.
				 */
				const parentPostContent = getBlockParentsByBlockName(
					selectedClientId,
					POST_CONTENT_BLOCK_NAME
				);

				let fnBlock = findFootnotesBlock(
					getBlocks,
					parentPostContent[ 0 ]
				);

				// Maybe this should all also be moved to the entity provider.
				// When there is no footnotes block in the post, create one and
				// insert it at the bottom.
				if ( ! fnBlock ) {
					let rootClientId = getBlockRootClientId( selectedClientId );

					while (
						rootClientId &&
						getBlockName( rootClientId ) !== POST_CONTENT_BLOCK_NAME
					) {
						rootClientId = getBlockRootClientId( rootClientId );
					}

					fnBlock = createBlock( 'core/footnotes' );

					insertBlock( fnBlock, undefined, rootClientId );
				}

				selectionChange( fnBlock.clientId, id, 0, 0 );
			} );
		}

		return (
			<RichTextToolbarButton
				name="footnote"
				icon={ icon }
				title={ __( 'Footnote' ) }
				onClick={ onClick }
				isActive={ isObjectActive }
			/>
		);
	},
};
