import { useEffect } from 'react'
import { useSceneContext } from '../../../sceneContext'
import { detectModifierKeys } from '../../../../../utils/shortcutkeys/detectModifierKeys';
import { useSocketStore, useToggleView } from '../../../../../store/builder/store';
import { useVersionContext } from '../../../../builder/version/versionContext';

import use2DUndoHandler from '../handlers/use2DUndoHandler';
import use2DRedoHandler from '../handlers/use2DRedoHandler';

function UndoRedo2DControls() {
    const { undoRedo2DStore } = useSceneContext();
    const { undoStack, redoStack } = undoRedo2DStore();
    const { toggleView } = useToggleView();
    const { handleUndo } = use2DUndoHandler();
    const { handleRedo } = use2DRedoHandler();
    const { socket } = useSocketStore();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();

    useEffect(() => {
        // console.log(undoStack, redoStack);
    }, [undoStack, redoStack]);

    useEffect(() => {
        const handleKeyDown = (event: KeyboardEvent) => {
            const keyCombination = detectModifierKeys(event);

            if (keyCombination === 'Ctrl+Z') {
                handleUndo();
            }

            if (keyCombination === 'Ctrl+Y') {
                handleRedo();
            }
        };

        if (toggleView) {
            window.addEventListener('keydown', handleKeyDown);
        }

        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, [toggleView, undoStack, redoStack, socket, selectedVersion]);

    return null;
}

export default UndoRedo2DControls;
