//@ts-ignore: Cannot find module '@wordpress/block-editor' or its corresponding type declarations.
import { BlockControls } from '@wordpress/block-editor';
//@ts-ignore: Cannot find module '@wordpress/components' or its corresponding type declarations.
import { ToolbarButton } from '@wordpress/components';
import { layout } from '@wordpress/icons';
//@ts-ignore: Cannot find module '@wordpress/blocks' or its corresponding type declarations.
import { createBlock } from '@wordpress/blocks';
//@ts-ignore: Cannot find module '@wordpress/data' or its corresponding type declarations.
import { useSelect, useDispatch } from '@wordpress/data';
import { useCallback } from '@wordpress/element';

import { IconScenePin } from '../../../icons';

interface Props {
    clientId: string;
}

export default function ButtonSceneWrapper({ clientId }: Props) {

    const parentClientNames = useSelect((select: any) => {
        const parentClientIds = select('core/block-editor').getBlockParents(clientId);
        return parentClientIds.map((id: string) => {
            const { name } = select('core/block-editor').getBlock(id) || {};
            return name;
        });
    }, [clientId]);
    const hasSceneAncestor =  parentClientNames.includes('scroll-sequence/v2-scene');
    const hasContainerAncestor = parentClientNames.includes('scroll-sequence/v2-container');

    const block = useSelect(
        (select:any) => select('core/block-editor').getBlock(clientId),
        [clientId]
    );
    const parentClientId = useSelect(
        (select:any) => select('core/block-editor').getBlockRootClientId(clientId),
        [clientId]
    );
    const blockIndex = useSelect(
        (select:any) => select('core/block-editor').getBlockIndex(clientId, parentClientId),
        [clientId, parentClientId]
    );

    const { removeBlock, insertBlock } = useDispatch('core/block-editor');

    const onWrap = useCallback(() => {
        if (!block) return;
        // Create the scene wrapper block with foo:bar attributes
        const wrapperBlock = createBlock('scroll-sequence/v2-scene', { 
           // foo: 'bar' // add any attributes you need here
        }, [block]);
        // Remove the original block and insert the wrapped block at the same position
        removeBlock(clientId, false);
        insertBlock(wrapperBlock, blockIndex, parentClientId);
    }, [block, clientId, parentClientId, blockIndex, removeBlock, insertBlock]);

    if (hasSceneAncestor) {
        return <></>; // Don't show the button if already inside a scene
    }

    return (
        <BlockControls>
            <ToolbarButton
                icon={IconScenePin}
                label="Wrap in Scrollsequence Scene"
                onClick={onWrap}
            />
        </BlockControls>
    );
}