//@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 { 
    __experimentalParseQuantityAndUnitFromRawValue as parseQuantityAndUnitFromRawValue,

    __experimentalUnitControl as UnitControl, 
    //@ts-ignore: Cannot find module '@wordpress/components' or its corresponding type declarations.
} from '@wordpress/components'

export default function WidthInput( { 
    onChange,
    onUnitChange,
    unit,
    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 units = useCustomUnits( { // does not allow "auto" unit, because I have just made it up.
    //     availableUnits: [ 'auto', 'px', 'em', 'rem', 'vw', '%' ],
    //     defaultValues: { auto: '', px: 430, '%': 50, em: 20, rem: 20, vw: 50, vh: 50 },
    // } );
    const units = [
        { value: 'auto',    label: 'Auto',  default: ' ' },
        { value: 'px',      label: 'px',    default: 400 },
        { value: 'em',      label: 'em',    default: 0 },
        { value: 'rem',     label: 'rem',   default: 20 },
        { value: 'vw',      label: 'vw',    default: 50 },
        { value: '%',       label: '%',     default: 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_WIDTH = 50;
    const min = isPx ? MIN_WIDTH : 0;

    return (
        <UnitControl
            __next40pxDefaultSize
            label={ __( 'Width', 'scrollsequence' ) }
            isResetValueOnUnitChange
            min={ min }
            onChange={ handleOnChange }
            onUnitChange={ onUnitChange }
            units={ units }
            value={ unit === 'auto' ? 'auto' : computedValue }
        />
    );
}