import { __ } from '@wordpress/i18n';
import { dispatch, useSelect } from '@wordpress/data';
import { createBlock } from '@wordpress/blocks';
import { BlockControls } from '@wordpress/block-editor';
import { DropdownMenu, Icon, ToolbarGroup } from '@wordpress/components';

const ControlsImage = (props) => {
    const {
        getBlockIndex,
        getSelectedBlock
    } = useSelect( 'core/block-editor' );

    const regenerateClickHandler = (props) => {
        const currentImageBlock = getSelectedBlock();
        const currentImageBlockIndex = getBlockIndex(currentImageBlock.clientId);
        const createdGenerateImageBlock = createBlock('seoaic/generate-image-block', {
            userPrompt: props.attributes.userPrompt ?? ''
        });

        dispatch('core/block-editor').insertBlock(
            createdGenerateImageBlock,
            currentImageBlockIndex + 1
        );

        // remove image block
        dispatch('core/block-editor').removeBlock(currentImageBlock.clientId);
    }

    return (
        <BlockControls>
            <ToolbarGroup>
                <DropdownMenu
                    icon={ <Icon
                        icon="screenoptions"
                        className="dashicons-admin-generic"
                    /> }
                    label={ __('SEOAI Commands', 'seoaic') }
                    controls={ [
                        {
                            title: __('Regenerate image', 'seoaic'),
                            onClick: () => {
                                console.log(props.attributes);
                                regenerateClickHandler(props);
                            },
                        }
                    ] }
                />
            </ToolbarGroup>
        </BlockControls>
    );
};

export default ControlsImage;