//@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, 
    ToggleControl,
    Notice,
    __experimentalToggleGroupControl as ToggleGroupControl,
    __experimentalToggleGroupControlOption as ToggleGroupControlOption,
    __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 { AttributesScene } from '../../types';
import { DVPT } from '../../../../../dbg';
import ScrollTriggerControlBlocks from '../../../../components/ScrollTriggerControlBlocks'
//@ts-ignore: Cannot find name 'wp'.
const { applyFilters, } = wp.hooks;



function PositionToggle({
    value,
    onChange,
}:{
    value: AttributesScene['scenePosition']
    onChange: any
}) {
    return (
        <ToggleGroupControl
            label={ __( 'Scene Position', 'scrollsequence' ) }
            value={value}
            onChange={onChange}
            isBlock
            __nextHasNoMarginBottom
            __next40pxDefaultSize
        >
            <ToggleGroupControlOption value="sticky" label="Sticky" />
            <ToggleGroupControlOption value="fixed" label="Fixed" />
        </ToggleGroupControl>
    );
}

function StickyTypeControl({
    value,
    onChange
}:{
    value: AttributesScene['stickyType']
    onChange: any
}) {
    return (
        <ToggleControl
            __nextHasNoMarginBottom
            label={ __( 'Sticky Mode', 'scrollsequence' ) }
            help={
                value === 'css'
                    ? '✔ Uses CSS Sticky. (default)'
                    : '✖ Uses Javascript Sticky. (FALLBACK)'
            }
            checked={ value==='css' }
            onChange={ onChange }
        />
    );   
}

function StickySpacingControl({
    value,
    onChange
}:{
    value: AttributesScene['stickySpacing']
    onChange: any
}) {
    return (
        <ToggleControl
            __nextHasNoMarginBottom
            label={ __( 'Spacing', 'scrollsequence' ) }
            help={
                value
                    ? 'Has spacing.'
                    : 'No spacing.'
            }
            checked={ value }
            onChange={ onChange }
        />
    );   
}

function SendBehindContentToggle({
    value,
    onChange
}:{
    value: AttributesScene['sendBehindContent']
    onChange: any
}) {
    return (
        <ToggleControl
            __nextHasNoMarginBottom
            label={ __( 'Send Behind Content', 'scrollsequence' ) }
            help={
                value
                    ? 'Moved to background.'
                    : 'Normal position.'
            }
            checked={ value }
            onChange={ onChange }
        />
    );   
}


function HeightInput( { 
    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={ __( 'Height', 'scrollsequence' ) }
            isResetValueOnUnitChange
            min={ min }
            onChange={ handleOnChange }
            onUnitChange={ onUnitChange }
            units={ units }
            value={ computedValue }
        />
    );
}




export default function InspectorControlsC2d({
    attributes, 
    setAttributes, 
    defaultAttributes, 
}:{
    attributes: AttributesScene
    setAttributes: any
    defaultAttributes: any
}){
    const { 
        scenePosition, 
        stickyType,
        stickySpacing,
        sendBehindContent,
        height, 
        heightUnit, 
        duration,
        durationUnit,
        top, 
        topUnit,

        absTop,
        absTopUnit,
    } = attributes


    const PlanF = applyFilters('scroll-sequence-test1', <div style={{border: "1px solid yellow"}}>Free</div> );
    
    return (
        <>
            <InspectorControls>
                <Panel>
                    <div style={{padding: "10px"}}>
                        <HeightInput
                            value={ height }
                            unit={ heightUnit }
                            onChange={ ( newheight:any ) =>
                                setAttributes( {
                                    height: newheight,
                                    // style:  { // trying to get rid of cleanEmptyObject()
                                    //     ...attributes?.style,
                                    //     dimensions: {
                                    //         ...attributes?.style?.dimensions,
                                    //         aspectRatio: undefined, // Reset aspect ratio when height is set.
                                    //     },
                                    // },
                                } )
                            }
                            onUnitChange={ ( nextUnit:any ) =>
                                setAttributes( {
                                    heightUnit: nextUnit,
                                } )
                            }
                        />

                        <UnitControl
                            __next40pxDefaultSize
                            label={ __( 'Duration (px)', 'scrollsequence' ) }
                            isResetValueOnUnitChange
                            onChange={ ( value:boolean, event:any, ) => {
                                // !!! TOHLE MOC NEFUNGUJE, ale to vime ...
                                //DVPT&&console.log('sendBehindContentControl onChange:', value, 'event',event, 'event?.event?.target?.value:',event?.event?.target?.value)
                                if (event?.event?.target?.value){
                                    setAttributes( { duration: Number(event.event.target.value) } )
                                }
                                
                            } } 
                            onUnitChange={ ( value:boolean ) => {
                                //DVPT&&console.log('sendBehindContentControl onUnitChange:', value)
                                setAttributes( { durationUnit: value } )
                            } } 
                            units={ [
                                { value: 'px', label: 'px', default: 0 },
                                //{ value: '%', label: '%', default: 10 },
                            ] }
                            value={ duration  }
                        />

                        <UnitControl
                            __next40pxDefaultSize
                            label={ __( 'Top', 'scrollsequence' ) }
                            isResetValueOnUnitChange
                            onChange={ ( value:boolean, event:any, ) => {
                                // !!! TOHLE MOC NEFUNGUJE, ale to vime ...
                                //DVPT&&console.log('sendBehindContentControl onChange:', value, 'event',event, 'event?.event?.target?.value:',event?.event?.target?.value)
                                if (event?.event?.target?.value){
                                    setAttributes( { top: Number(event.event.target.value) } )
                                }
                                
                            } } 
                            onUnitChange={ ( value:boolean ) => {
                                //DVPT&&console.log('sendBehindContentControl onUnitChange:', value)
                                setAttributes( { topUnit: value } )
                            } } 
                            units={ [
                                { value: 'px', label: 'px', default: 0 },
                                { value: '%', label: '%', default: 10 },
                            ] }
                            value={ top  }
                        />

                        <PositionToggle 
                            value={ scenePosition }
                            onChange={ ( nextPosition:any ) =>{
                                DVPT&&console.log('PositionToggle onChange:', nextPosition)
                                setAttributes( { scenePosition: nextPosition } )
                            }}
                        />
                        { scenePosition === 'sticky' && (    
                            <>
                                <StickyTypeControl
                                    value={ stickyType }
                                    onChange={ ( nextType:boolean ) => {
                                        DVPT&&console.log('StickyTypeControl onChange:', nextType)
                                        setAttributes( { stickyType: nextType ? 'css': 'js'} )
                                    } }
                                />
                                <StickySpacingControl
                                    value={ stickySpacing }
                                    onChange={ ( nextSpacing:boolean ) => {
                                        DVPT&&console.log('StickySpacingControl onChange:', nextSpacing)
                                        setAttributes( { stickySpacing: nextSpacing } )
                                    } }
                                />                            
                            </>
                        )}

                        {/* REMOVING SENDBEHINDCONTENT TOGGLE FOR NOW

                        <SendBehindContentToggle
                            value={ sendBehindContent }
                            onChange={ ( nextValue:boolean ) => {
                                DVPT&&console.log('sendBehindContentControl onChange:', nextValue)
                                setAttributes( { sendBehindContent: nextValue } )
                            } }                    
                        />
                        { sendBehindContent && scenePosition === 'sticky' && (
                            <UnitControl
                                __next40pxDefaultSize
                                label={ __( 'Top Offset', 'scrollsequence' ) }
                                isResetValueOnUnitChange
                                onChange={ ( value:boolean, event:any, ) => {
                                    // !!! TOHLE MOC NEFUNGUJE, ale to vime ...
                                    //DVPT&&console.log('sendBehindContentControl onChange:', value, 'event',event, 'event?.event?.target?.value:',event?.event?.target?.value)
                                    if (event?.event?.target?.value){
                                        setAttributes( { absTop: Number(event.event.target.value) } )
                                    }
                                    
                                } } 
                                onUnitChange={ ( value:boolean ) => {
                                    //DVPT&&console.log('sendBehindContentControl onUnitChange:', value)
                                    setAttributes( { absTopUnit: value } )
                                } } 
                                units={ [
                                    { value: 'px', label: 'px', default: 0 },
                                    { value: '%', label: '%', default: 10 },
                                ] }
                                value={ absTop  }
                            />
                        )}

                        */}

                    </div>
                </Panel>
                <Panel>
                    <PanelBody title={__("Animation Trigger", "scrollsequence")} initialOpen={true}>
                        <ScrollTriggerControlBlocks attributes={attributes} setAttributes={setAttributes} defaultAttributes={defaultAttributes} />
                    </PanelBody>
                </Panel>
                {/* <Panel>
                    <PanelBody title={__('Scene Height', 'scrollsequence')} initialOpen={true}>

                    </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">
                __min_height_was_here_
            </InspectorControls> */}

            {/* <InspectorControls group="advanced">
                    __HTML_tag_selection__
            </InspectorControls> */}
        </>
    )
}
