import { useState } from 'react';
//@ts-ignore: Cannot find module '@wordpress/i18n' or its corresponding type declarations.
import { __ } from '@wordpress/i18n';
import {  useEffect, useRef } from '@wordpress/element'
//@ts-ignore: Cannot find module '@wordpress/block-editor' or its corresponding type declarations.
import { useBlockProps, useInnerBlocksProps, store as blockEditorStore, } from '@wordpress/block-editor';
//@ts-ignore: Cannot find module '@wordpress/data' or its corresponding type declarations.
import { useSelect } from '@wordpress/data';
import { chevronLeft } from '@wordpress/icons';
//@ts-ignore: Cannot find module '@wordpress/components' or its corresponding type declarations.
import { Placeholder, Button, __experimentalHStack as HStack, } from '@wordpress/components'
//import {addImageGroupWpMedia, addImageGroupUrlList, addImageGroupGap } from './inspector-controls/media-groups-manager/addImageGroup'
import { addMediaGroup } from '../../../../shared/media-2d/addMediaGroup';
import { AttributesCanvas2d } from '../types';

import ToolsContextProvider from './media3tools/ContextProvider';
import PlaceholderEmptyMedia from '../../../../shared/media-2d/components/PlaceholderEmptyMedia';

import InspectorControls from './inspector-controls';
import BlockControls from './block-controls';
import { IconCanvas2d } from '../../../../icons'
import getScrollsequenceFop from '../../../getScrollsequenceFop';
import { DC2D } from '../../../../dbg'

import MediaToolsX from './media3tools/media3tools';
/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {WPElement} Element to render.
 */
interface EditProps {
    clientId: string,
    attributes: AttributesCanvas2d,
    setAttributes: any,
    name: string,
    onRemove: any, //  () => removeBlock(clientId)
    onReplace: any, //  (...args) => {…}
    // ... more attributes
    
}
export default function Edit(props:EditProps) {
    const { 
        clientId,
        attributes, 
        setAttributes,
        attributes:{
            mediaGroups,
            //... more attributes
        }, 
        onRemove,
        onReplace,
    } = props;

    const defaultAttributes = useSelect((select:any) => { // Access the default values
        return select('core/blocks').getBlockType('scroll-sequence/v2-canvas2d').attributes
    }, []); //console.log('defaultAttributes',defaultAttributes)

    // Assign width and height with default values if not set - (this happens in three places. editor, editor component and front end render.php)
    const width = attributes.width ? attributes.width : '100';
    const widthUnit = attributes.widthUnit ? attributes.widthUnit : '%';
    const isAutoWidth = (widthUnit === 'auto') ? true : false;

    const height = attributes.height ? attributes.height : '75';
    const heightUnit = attributes.heightUnit ? attributes.heightUnit : 'vh';

    const elRef = useRef<any>(null)
    const blockProps = useBlockProps({
        style: {
            width:  isAutoWidth ? undefined : `${ width }${ widthUnit }`,
            height: `${ height }${ heightUnit }`,
            // FAKE "sendToBackground" for 2D canvas - START
                // position: 'absolute',
                // top: 0,
                // left: 0,
                // zIndex: 0,
                // overflow: 'hidden',
                // pointerEvents: 'none',
            // FAKE "sendToBackground" for 2D canvas - END 

        },
        //className: `ssq-relative`
        ref: elRef
    });

    const hasMediaGroups = (mediaGroups.length < 1) ? false : true;

    const [ indexActiveGroup, setIndexActiveGroup ] = useState(0); // this is drilling down to inspector controls

    //const [ showMediaGroupAdder, setShowMediaGroupAdder ] = useState(hasMediaGroups ? false : true); 
    //const [ mediaGroupDisplay, setMediaGroupDisplay ] = useState<'adder' | 'c2dTools' >('adder'); // for the editor only, not saved in attributes
    const [ show, setShow ] = useState<'canvas' | 'adder' | 'media-tools'>(hasMediaGroups ? 'canvas' : 'adder'); // initial value depends if there are media groups already

    // PREVIEW MODE 
    const isPreview = useSelect( ( select:any ) => {
        const settings = select('core/block-editor').getSettings?.() || {};
        // WP 6.8+: isPreviewMode is stable; fall back for older versions.
        return settings.isPreviewMode ?? settings.__unstableIsPreviewMode ?? false;
    }, [] );
    const attributesForPreview = isPreview && JSON.parse(JSON.stringify(attributes));
    if ( isPreview ) {
        // remove all media groups except the first one
        if (attributesForPreview.mediaGroups && attributesForPreview.mediaGroups.length > 1) {
            attributesForPreview.mediaGroups = [attributesForPreview.mediaGroups[0]];
        }
        // if check if the only remaining media group is type===wpMedia or urlList and if yes, remove all images except the first TWO  
        if (attributesForPreview.mediaGroups && attributesForPreview.mediaGroups.length === 1) {
            const mediaGroup = attributesForPreview.mediaGroups[0];
            if (mediaGroup.type === 'wpMedia' || mediaGroup.type === 'urlList') {
                attributesForPreview.mediaGroups[0].images = [
                    attributesForPreview.mediaGroups[0].images[0],
                    //attributesForPreview.mediaGroups[0].images[1] // keep the first two images, not needed, works now even for 1 frame.
                ];
            }
        }
        DC2D&&console.log('canvas2d edit isPreview',isPreview, 'attributesForPreview',attributesForPreview, )
    }
    
    
   
    useEffect(() => {

        // show canvas if we have media groups
        if ( show === 'canvas' && hasMediaGroups ) {
            DC2D&&console.log('canvas2d useEffect[attributes] elRef.current.id',elRef.current?.id)
            getScrollsequenceFop(elRef.current)?.createBlock(elRef.current);
            getScrollsequenceFop(elRef.current)?.preloadAll(); // added
        } 

        // if we don't have media groups, and someone is trying to switch to canvas, force adder
        // if ( show === 'canvas' && !hasMediaGroups ) {
        //     setShow('adder');
        // }

        return () => {
            DC2D&&console.log('canvas2d useEffect[attributes] CLEANUP elRef.current.id',elRef.current?.id)
            getScrollsequenceFop(elRef.current)?.destroyBlock(elRef.current)
        };        
    }, [attributes, show]);	

    return (
        <>
            <ToolsContextProvider >          
                <BlockControls
                    clientId={clientId}
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    hasMediaGroups={hasMediaGroups}
                    defaultAttributes={defaultAttributes}
                    show={show}
                    setShow={setShow}
                    
                />        
            
                <InspectorControls 
                    clientId={clientId}
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    defaultAttributes={defaultAttributes} 
                    hasMediaGroups={hasMediaGroups}
                    indexActiveGroup={indexActiveGroup}
                    setIndexActiveGroup={setIndexActiveGroup}
                />        
                { hasMediaGroups && show === 'canvas' 
                ?
                    <div {...blockProps} data-ssq-canvas2d={JSON.stringify( isPreview ? attributesForPreview : attributes)}  >
                        <canvas></canvas>
                    </div>
                :		
                    <div {...blockProps} style={{...blockProps.style, width: '100%', height: 'auto', zIndex:99999}}>

                            { ( show === 'adder' || show === 'canvas') &&(
                                <Placeholder
                                    icon={ IconCanvas2d }
                                    label={__('Canvas 2D ','scrollsequence')}
                                    isColumnLayout={ true }
                                >
                                    <p>{__('Add Media Group to the Canvas','scrollsequence')}</p>
                                    <PlaceholderEmptyMedia 
                                        renderComplexUi={false} 
                                        attributes={attributes}
                                        setAttributes={setAttributes}
                                        
                                        setIndexActiveGroup={setIndexActiveGroup}

                                        setShow={setShow}
                                    />     
                                </Placeholder>
                            )}
                            { show === 'media-tools' && (
                                <Placeholder
                                    isColumnLayout={ true }
                                >
                                    <MediaToolsX attributes={attributes}  setAttributes={setAttributes}  setShow={setShow} />
                                </Placeholder>
                            )}
                            
                    </div>
                }        
            </ToolsContextProvider>
        </>
    )
}
