/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
import { BlockControls } from '@wordpress/block-editor';
import { SVG, ToolbarGroup, ToolbarDropdownMenu } from '@wordpress/components';

const icon = () => (
	<SVG width="24" height="24" viewBox="0 0 24 24">
		<path d="M9.16601 4H10V5.5H9.16601C8.74401 5.5 8.25901 5.86 8.14001 6.543L7.63601 9.443C7.54684 9.96776 7.31701 10.4585 6.97101 10.863L6.00001 12L6.97301 13.138C7.31601 13.536 7.54301 14.028 7.63601 14.557L8.14001 17.457C8.25901 18.141 8.74401 18.5 9.16601 18.5H10V20H9.16601C7.87201 20 6.87901 18.965 6.66201 17.714L6.15801 14.815C6.11566 14.5585 6.00514 14.3181 5.83801 14.119L5.83701 14.118L3.99701 12L5.83901 9.88C5.99401 9.701 6.10901 9.46 6.15901 9.185L6.66201 6.287C6.87901 5.035 7.87201 4 9.16601 4ZM17.838 9.185L17.334 6.287C17.117 5.035 16.124 4 14.83 4H13.996V5.5H14.83C15.252 5.5 15.738 5.86 15.856 6.543L16.36 9.443C16.452 9.967 16.679 10.465 17.025 10.863L17.996 12L17.023 13.138C16.6782 13.5426 16.4491 14.0329 16.36 14.557L15.856 17.457C15.738 18.141 15.252 18.5 14.83 18.5H13.996V20H14.83C16.125 20 17.117 18.965 17.334 17.714L17.838 14.815C17.886 14.542 18.002 14.301 18.158 14.119L18.159 14.118L20 12L18.157 9.88C17.9902 9.68121 17.88 9.44113 17.838 9.185Z" />
	</SVG>
)

const MergeTagsBlockControl = ( { tags, attributes, setAttributes } ) => {
	const { clientId, selectionStart, selectionEnd } = useSelect( select => ( {
		clientId: select( 'core/block-editor' ).getSelectedBlockClientId(),
		selectionStart: select( 'core/block-editor' ).getSelectionStart(),
		selectionEnd: select( 'core/block-editor' ).getSelectionEnd(),
	} ) );

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

	// Bail if it's a multi-block selection.
	if ( selectionStart.clientId !== selectionEnd.clientId ) {
		return null;
	}

	return (
		<BlockControls>
			<ToolbarGroup>
				<ToolbarDropdownMenu
					icon={ icon }
					label={ __( 'Merge tags', 'newspack-popups' ) }
					menuProps={ { className: "newspack-popups__merge-tags-menu" } }
					controls={ tags.map( ( tag ) => (
						{
							title: tag.description,
							onClick: () => {
								const text = `{{${tag.name.toUpperCase()}}}`;
								const newContent =
									attributes.content.slice( 0, selectionStart.offset ) +
									text +
									attributes.content.slice( selectionEnd.offset );

								const cursorPosition = selectionStart.offset + text.length;

								setAttributes( { content: newContent } );
								selectionChange( clientId, 'content', cursorPosition, cursorPosition );
							},
						}
					) ) }
				/>
			</ToolbarGroup>
		</BlockControls>
	)
};

export default MergeTagsBlockControl;
