const { useState, useEffect } = wp.element;
const { ColorPicker } = wp.components;

const SafiColorPicker = ( { color, alpha, onColorChange, onColorChangeComplete, onTriggerSnapshot, ...props } ) => {
    const [currentColor, setCurrentColor] = useState( color );
    const [hexInputValue, setHexInputValue] = useState( color ? color.replace('#', '') : '' );
    const [showColorPicker, setShowColorPicker] = useState( false );
    const [recentColors, setRecentColors] = useState( [] );
    const [initialColor, setInitialColor] = useState( null );
    const [colorChanged, setColorChanged] = useState( false );

    useEffect( () => {
        setCurrentColor( color );
        setHexInputValue( color ? color.replace('#', '') : '' );
    }, [color] );

    useEffect( () => {
        // Load recent colors from localStorage
        const savedColors = localStorage.getItem( 'SAFI_COLORS' );
        if ( savedColors ) {
            try {
                setRecentColors( JSON.parse( savedColors ) );
            } catch ( error ) {
                console.error( 'Error parsing saved colors:', error );
                setRecentColors( [] );
            }
        }
    }, [] );

    const twoDigits = ( number ) => {
        return ( "0" + number ).slice( -2 );
    }

    const isValidHexColor = ( hex ) => {
        // Remove # if present
        hex = hex.replace('#', '');
        // Check if it's a valid hex color (3, 4, 6, or 8 characters)
        return /^([A-Fa-f0-9]{3}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test( hex );
    };

    const normalizeHexColor = ( hex ) => {
        hex = hex.replace('#', '').toUpperCase();
        
        // Convert 3-digit hex to 6-digit
        if ( hex.length === 3 ) {
            hex = hex.split('').map(char => char + char).join('');
        }
        // Convert 4-digit hex to 8-digit (with alpha)
        else if ( hex.length === 4 ) {
            hex = hex.split('').map(char => char + char).join('');
        }
        
        return '#' + hex;
    };

    const saveColorToRecent = ( colorValue ) => {
        if ( !colorValue ) return;

        const colorToSave = colorValue.startsWith('#') ? colorValue : '#' + colorValue;
        
        // Get current recent colors
        let updatedColors = [...recentColors];
        
        // Remove color if it already exists
        updatedColors = updatedColors.filter( c => c !== colorToSave );
        
        // Add new color to the beginning
        updatedColors.unshift( colorToSave );
        
        // Keep only the latest 10
        updatedColors = updatedColors.slice( 0, 10 );
        
        setRecentColors( updatedColors );
        localStorage.setItem( 'SAFI_COLORS', JSON.stringify( updatedColors ) );
    };

    const handleChange = ( color ) => {
        setCurrentColor( color );
        const hexValue = color ? color.replace('#', '') : '';
        setHexInputValue( hexValue );
        
        // Mark that color has been changed
        setColorChanged( true );

        if ( onColorChange ) {
            onColorChange( color );
        }
    };

    const handleHexInputChange = ( e ) => {
        const value = e.target.value.replace('#', '');
        setHexInputValue( value );
    };

    const handleHexInputBlur = () => {
        if ( hexInputValue === '' ) {
            setCurrentColor( undefined );
            setColorChanged( true );
            if ( onColorChangeComplete ) {
                onColorChangeComplete( undefined );
            }
            return;
        }

        if ( isValidHexColor( hexInputValue ) ) {
            const normalizedColor = normalizeHexColor( hexInputValue );
            setCurrentColor( normalizedColor );
            setHexInputValue( normalizedColor.replace('#', '') );
            setColorChanged( true );
            
            if ( onColorChangeComplete ) {
                onColorChangeComplete( normalizedColor );
            }
            
            // Save to recent colors immediately for direct input
            saveColorToRecent( normalizedColor );
        } else {
            // Revert to current color if invalid
            setHexInputValue( currentColor ? currentColor.replace('#', '') : '' );
        }
    };

    const handleHexInputKeyDown = ( e ) => {
        if ( e.key === 'Enter' ) {
            e.target.blur();
        }
    };

    const handleHexInputFocus = ( e ) => {
        e.target.select();
    };

    const handleClick = () => {
        if ( !showColorPicker ) {
            // Store the initial color when opening the picker
            setInitialColor( currentColor );
            setColorChanged( false );
        }
        setShowColorPicker( !showColorPicker );
    };

    const handleClose = () => {
        // Only save to recent colors if the color actually changed
        if ( colorChanged && currentColor && currentColor !== initialColor ) {
            saveColorToRecent( currentColor );
        }
        
        setShowColorPicker( false );
        setColorChanged( false );
        setInitialColor( null );
    };

    const handleMouseDown = ( e ) => {
        onTriggerSnapshot();
    };

    const handleMouseUp = ( e ) => {
        if ( onColorChangeComplete ) {
            onColorChangeComplete( currentColor );
            // Don't save to recent colors here anymore - will be handled on popup close
        }
    };

    const handleRecentColorClick = ( recentColor ) => {
        setCurrentColor( recentColor );
        setHexInputValue( recentColor.replace('#', '') );
        
        if ( onColorChangeComplete ) {
            onColorChangeComplete( recentColor );
        }
        
        // Save this color selection and close the popup
        saveColorToRecent( recentColor );
        setShowColorPicker( false );
        setColorChanged( false );
        setInitialColor( null );
    };

    const popover = {
        backgroundColor: 'white',
        position: 'absolute',
        zIndex: '2',
        right: 'calc(100% + 10px)',
        top: 'calc(50% - 200px)',
        padding: '8px',
        borderRadius: '8px',
        boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
    };

    const cover = {
        position: 'fixed',
        top: '0px',
        right: '0px',
        bottom: '0px',
        left: '0px',
    };

    const reset = () => {
        const resetColor = undefined;
        setCurrentColor( resetColor );
        setHexInputValue( '' );

        if ( onColorChangeComplete ) {
            onColorChangeComplete( resetColor );
        }
    };

    return (
        <div className="safi-input">
            <div className="safi-colorpicker--container">
                <div
                    className="color-sample"
                    onClick={handleClick}
                    style={{
                        backgroundColor: currentColor || 'transparent',
                    }}
                />
                <div className="color-hex">
                    <input
                        type="text"
                        className="color-hex-input"
                        value={hexInputValue}
                        onChange={handleHexInputChange}
                        onBlur={handleHexInputBlur}
                        onKeyDown={handleHexInputKeyDown}
                        onFocus={handleHexInputFocus}
                        placeholder="000000"
                    />
                </div>
                {showColorPicker ?
                    <div style={popover} >
                        <div
                            className="overlayCP"
                            style={cover}
                            onClick={handleClose}
                        />
                        <div className="color-picker-popup">
                            <ColorPicker
                                color={currentColor || undefined}
                                onChange={handleChange}
                                onMouseDown={handleMouseDown}
                                onMouseUp={handleMouseUp}
                                enableAlpha
                                defaultValue="#000"
                            />
                            
                            {recentColors.length > 0 && (
                                <div className="recent-colors">
                                    <div className="recent-colors-label">Recent Colors:</div>
                                    <div className="recent-colors-grid">
                                        {recentColors.map( ( recentColor, index ) => (
                                            <div
                                                key={index}
                                                className="recent-color-item"
                                                style={{ backgroundColor: recentColor }}
                                                onClick={() => handleRecentColorClick( recentColor )}
                                                title={recentColor}
                                            />
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div> : null}
                <span
                    title="Clear"
                    className={"safi-box-control-icon icon-clear dashicons"}
                    onMouseDown={reset}
                ></span>
            </div>
        </div>
    );
};

export default SafiColorPicker;