//@ts-ignore: Cannot find module '@wordpress/i18n' or its corresponding type declarations.
import { __ } from '@wordpress/i18n';
//@ts-ignore: Cannot find module '@wordpress/element' or its corresponding type declarations.
import { useMemo } from '@wordpress/element';
import { 
    InspectorControls, 
    useSettings, 
    //@ts-ignore: Cannot find module '@wordpress/block-editor' or its corresponding type declarations.
} from '@wordpress/block-editor';
import { 
    Panel, 
    PanelBody, 
    SelectControl,
    TextControl,
    ExternalLink ,
    __experimentalParseQuantityAndUnitFromRawValue as parseQuantityAndUnitFromRawValue,
    __experimentalUseCustomUnits as useCustomUnits,
    __experimentalUnitControl as UnitControl, 
    //@ts-ignore: Cannot find module '@wordpress/components' or its corresponding type declarations.
} from '@wordpress/components'

import ScrollTriggerControlBlocks from '../../../../components/ScrollTriggerControlBlocks'
//import PinControl from '../../../../components/PinControl'
import { AttributesCanvas1d } from '../../types';

//@ts-ignore: Cannot find name 'wp'.
const { applyFilters, doAction, createHooks } = wp.hooks;

function SimpleHeightInput( { 
    onChange,
    onUnitChange,
    unit = 'px',
    value = '',
} :any ) {
    // Simplified WP Function from Cover Block (see: CoverHeightInput)
    // Compared to Cover block -> itdoes not have the option in the parent "dimensions" tab to reset, but it is simpler. ( no clientId is needed)
    const isPx = unit === 'px';
    const [ availableUnits ] = useSettings( 'spacing.units' );
    const units = useCustomUnits( {
        availableUnits: availableUnits || [ 'px', 'em', 'rem', 'vw', 'vh' ],
        defaultValues: { px: 430, '%': 20, em: 20, rem: 20, vw: 20, vh: 50 },
    } );

    const handleOnChange = ( unprocessedValue:any ) => {
        const inputValue =
            unprocessedValue !== ''
                ? parseFloat( unprocessedValue )
                : undefined;

        if ( isNaN( inputValue! ) && inputValue !== undefined ) {
            return;
        }
        onChange( inputValue );
    };

    const computedValue = useMemo( () => {
        const [ parsedQuantity ] = parseQuantityAndUnitFromRawValue( value );
        return [ parsedQuantity, unit ].join( '' );
    }, [ unit, value ] );

    const MIN_HEIGHT = 50;
    const min = isPx ? MIN_HEIGHT : 0;

    return (
        <UnitControl
            __next40pxDefaultSize
            label={ __( 'Minimum height', 'scrollsequence' ) }
            //id={ inputId }
            isResetValueOnUnitChange
            min={ min }
            onChange={ handleOnChange }
            onUnitChange={ onUnitChange }
            units={ units }
            value={ computedValue }
        />
    );
}

function getEditUrlFromSplinecodeUrl( splinecodeurl:string ){
    if ( !splinecodeurl ) {
        return undefined;
    }
    const url = new URL( splinecodeurl );
    const urlArray = url.pathname.split('/')
    
    const hash = urlArray[Math.max(0, urlArray.length - 2)]
    console.log('urlArray:',urlArray, 'hash:',hash)
    return `https://app.spline.design/file/${hash}`;
}

export default function InspectorControlsCanvas({
    attributes, 
    setAttributes, 
    defaultAttributes, 
    localValueSplineCodeUrl,
    setLocalValueSplineCodeUrl,
}:{
    attributes: AttributesCanvas1d
    setAttributes: any
    defaultAttributes: any 
    localValueSplineCodeUrl?:string
    setLocalValueSplineCodeUrl:any
}){
    const { 
        height, 
        heightUnit, 
        //splinecodeurl
    } = attributes


    const PlanF = applyFilters('scroll-sequence-test3d', <div style={{border: "1px solid yellow"}}>Free (3dv2)</div> );

    //console.log('splinecodeurl:',splinecodeurl,'editUrl:', getEditUrlFromSplinecodeUrl( splinecodeurl ) )
    
    return (
        <>
            <InspectorControls>
                <Panel>
                    <PanelBody title={__('Spline URL', 'scrollsequence')} initialOpen={true}>
                        <TextControl
                            label="Spline code URL"
                            value={ localValueSplineCodeUrl }
                            onChange={ (value : string ) => {
                                setLocalValueSplineCodeUrl(  value  )
                            }}
                        />
                        {/* {splinecodeurl&&(
                            <ExternalLink 
                                href={getEditUrlFromSplinecodeUrl(splinecodeurl)}
                                target="_blank"
                                rel="noopener noreferrer"
                            >
                               Edit in Spline
                            </ExternalLink>
                        )} */}
                    </PanelBody>
                </Panel>
                <Panel>
                    <PanelBody title={__("Animation Trigger", "scrollsequence")} initialOpen={true}>
                        <ScrollTriggerControlBlocks attributes={attributes} setAttributes={setAttributes} defaultAttributes={defaultAttributes} />
                    </PanelBody>
                </Panel>
                {/* <Panel>
                    <PanelBody title={__("Pinning", "scrollsequence")} initialOpen={false}>
                        <PinControl attributes={attributes} setAttributes={setAttributes} defaultAttributes={defaultAttributes} />
                    </PanelBody>
                </Panel>      */}

                <Panel>
                    <PanelBody title={__("Debug ", "scrollsequence")} initialOpen={false}>
                        <p>Attributes:</p>
                        <pre>{JSON.stringify(attributes, null, 2)}</pre>
                        <p>Plan (filter):</p>
                        {PlanF}
                    </PanelBody>
                </Panel>        
            </InspectorControls>

            {/* <InspectorControls group="color">
                ____Color_____
            </InspectorControls> */}

            <InspectorControls group="dimensions">
                <SimpleHeightInput
                    value={
                        attributes?.style?.dimensions?.aspectRatio
                            ? ''
                            : height
                    }
                    unit={ heightUnit }
                    onChange={ ( newheight:any ) =>
                        setAttributes( {
                            height: newheight,
                        } )
                    }
                    onUnitChange={ ( nextUnit:any ) =>
                        setAttributes( {
                            heightUnit: nextUnit,
                        } )
                    }
                />
            </InspectorControls>

            {/* <InspectorControls group="advanced">
                    TADY SE DAVAL TEN ELEMENT SELECT
            </InspectorControls> */}
        </>
    )
}
