import { useCallback } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { createBlock } from '@wordpress/blocks';

/**
 * Toolbar actions for a list item: insert a sibling item below, and add/select a
 * nested sub-list. Also reports the current nested-block count.
 *
 * @param {string} clientId The list-item's client ID.
 */
export function useListItemActions( clientId ) {
	const { insertBlocks, selectBlock } = useDispatch( 'core/block-editor' );

	const { parentClientId, blockIndex, nestedBlockCount, firstNestedBlockId } = useSelect(
		( select ) => {
			const editor = select( 'core/block-editor' );
			const nestedBlocks = editor.getBlocks( clientId );
			return {
				parentClientId: editor.getBlockRootClientId( clientId ),
				blockIndex: editor.getBlockIndex( clientId ),
				nestedBlockCount: nestedBlocks.length,
				firstNestedBlockId: nestedBlocks[ 0 ]?.clientId || null,
			};
		},
		[ clientId ]
	);

	const insertListItemAfter = useCallback( () => {
		if ( ! parentClientId || blockIndex < 0 ) {
			return;
		}
		const newItem = createBlock( 'axcelersblocks/list-item' );
		insertBlocks( newItem, blockIndex + 1, parentClientId, true );
		if ( newItem?.clientId ) {
			selectBlock( newItem.clientId );
		}
	}, [ insertBlocks, selectBlock, parentClientId, blockIndex ] );

	const insertNestedList = useCallback( () => {
		if ( nestedBlockCount > 0 ) {
			if ( firstNestedBlockId ) {
				selectBlock( firstNestedBlockId );
			}
			return;
		}
		const nestedList = createBlock( 'axcelersblocks/list' );
		insertBlocks( nestedList, 0, clientId, true );
		if ( nestedList?.clientId ) {
			selectBlock( nestedList.clientId );
		}
	}, [ insertBlocks, selectBlock, clientId, nestedBlockCount, firstNestedBlockId ] );

	return { insertListItemAfter, insertNestedList, nestedBlockCount };
}
