import { __ } from '@wordpress/i18n';
import { Button } from '@wordpress/components';
import { plus } from '@wordpress/icons';
import { useRegistry } from '@wordpress/data';
import { store as blockEditorStore } from '@wordpress/block-editor';
import { useCallback } from '@wordpress/element';
import { CHILD_NAME, makeColumnWidthAttrs } from '../structures';
import { createBlock } from '@wordpress/blocks';

/**
 * "+ Add Column" affordance rendered as the columns' trailing appender. It adapts
 * to the layout: a vertical bar on the right for a horizontal row, a horizontal
 * bar at the bottom when the columns stack (CSS: align-self: stretch).
 *
 * Adds one column and redistributes all columns to equal widths.
 */
export default function AddColumnAppender( { clientId, flexDirection } ) {
	const registry = useRegistry();

	const onAdd = useCallback( () => {
		const sel = registry.select( blockEditorStore );
		const dispatch = registry.dispatch( blockEditorStore );
		const order = sel.getBlockOrder( clientId );
		const pct = Math.round( ( 100 / ( order.length + 1 ) ) * 100 ) / 100;

		// Append the new column with the equal width; the parent's effect
		// re-equalizes the existing columns to match the new count.
		dispatch.insertBlocks( createBlock( CHILD_NAME, makeColumnWidthAttrs( pct, flexDirection ) ), order.length, clientId, false );
	}, [ registry, clientId, flexDirection ] );

	const stopEditorSelection = useCallback( ( event ) => {
		event.stopPropagation();
	}, [] );

	const onClick = useCallback( ( event ) => {
		event.preventDefault();
		event.stopPropagation();
		onAdd();
	}, [ onAdd ] );

	return (
		<Button
			className="axcelersblocks-columns__add-column"
			icon={ plus }
			label={ __( 'Add Column', 'axcelersblocks' ) }
			showTooltip
			onPointerDown={ stopEditorSelection }
			onMouseDown={ stopEditorSelection }
			onClick={ onClick }
		/>
	);
}
