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

const useListChildrenSync = ({
	clientId,
	childName = 'axcelersblocks/list-item',
	minimum = 1,
}) => {
	const children = useSelect(
		(select) => select('core/block-editor').getBlocks(clientId),
		[clientId]
	);

	const { replaceInnerBlocks } = useDispatch('core/block-editor');

	useEffect(() => {
		if (!Array.isArray(children)) {
			return;
		}

		if (children.length >= minimum) {
			return;
		}

		const next = [...children];

		for (let i = children.length; i < minimum; i++) {
			next.push(createBlock(childName));
		}

		replaceInnerBlocks(clientId, next, false);
	}, [children, clientId, childName, minimum, replaceInnerBlocks]);
};

export default useListChildrenSync;