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 useModuleStore from '../../../../../store/useModuleStore';

import use3DUndoHandler from '../handlers/use3DUndoHandler';
import use3DRedoHandler from '../handlers/use3DRedoHandler';

function UndoRedo3DControls() {
    const { undoRedo3DStore } = useSceneContext();
    const { undoStack, redoStack } = undoRedo3DStore();
    const { toggleView } = useToggleView();
    const { activeModule } = useModuleStore();
    const { handleUndo } = use3DUndoHandler();
    const { handleRedo } = use3DRedoHandler();
    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, activeModule]);

    return null;
}

export default UndoRedo3DControls;