import { useCallback } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { useStoreApi } from '@xyflow/react';
import useMindMapStore, { RFState } from '../store';
import { useShallow } from 'zustand/shallow';

const controlsSelector = (state: RFState) => ({
    selectedNodeId: state.selectedNodeId,
    setSelectedNodeId: state.setSelectedNodeId,
    addChildNode: state.addChildNode,
    addSiblingNode: state.addSiblingNode,
    undo: state.undo,
    redo: state.redo,
});

export function useFlowKeyboardControls() {
    const {
        selectedNodeId,
        setSelectedNodeId,
        addChildNode,
        addSiblingNode,
        undo,
        redo,
    } = useMindMapStore(useShallow(controlsSelector));

    const store = useStoreApi();

    const getNextNodeInDirection = useCallback((direction: 'left' | 'right' | 'up' | 'down') => {
        const { nodeLookup, edges } = store.getState();
        if (!selectedNodeId) return null;

        const currentNode = nodeLookup.get(selectedNodeId);
        if (!currentNode) return null;

        // 构建节点关系图
        const nodeRelations = new Map<string, { parent: string | null; children: string[]; siblings: string[] }>();

        edges.forEach(edge => {
            const source = edge.source;
            const target = edge.target;

            if (!nodeRelations.has(source)) {
                nodeRelations.set(source, { parent: null, children: [], siblings: [] });
            }
            if (!nodeRelations.has(target)) {
                nodeRelations.set(target, { parent: null, children: [], siblings: [] });
            }

            nodeRelations.get(target)!.parent = source;
            nodeRelations.get(source)!.children.push(target);
        });

        // 找出同级节点
        const currentRelation = nodeRelations.get(selectedNodeId);
        if (currentRelation?.parent) {
            const parentRelation = nodeRelations.get(currentRelation.parent);
            if (parentRelation) {
                currentRelation.siblings = parentRelation.children.filter(id => id !== selectedNodeId);
            }
        }

        // 根据方向决定下一个节点
        switch (direction) {
            case 'left': {
                // 如果当前节点是子节点，优先选择父节点
                if (currentRelation?.parent) {
                    const parentNode = nodeLookup.get(currentRelation.parent);
                    if (parentNode && parentNode.position.x < currentNode.position.x) {
                        return currentRelation.parent;
                    }
                }
                break;
            }
            case 'right': {
                // 如果有子节点，选择第一个子节点
                const children = currentRelation?.children || [];
                if (children.length > 0) {
                    return children[0];
                }
                break;
            }
            case 'up': {
                // 在同级节点中找位置靠上的节点
                const siblings = currentRelation?.siblings || [];
                const upperSiblings = siblings
                    .map(id => nodeLookup.get(id))
                    .filter(node => node && node.position.y < currentNode.position.y)
                    .sort((a, b) => b!.position.y - a!.position.y);

                if (upperSiblings.length > 0) {
                    return upperSiblings[0]!.id;
                }
                break;
            }
            case 'down': {
                // 在同级节点中找位置靠下的节点
                const siblings = currentRelation?.siblings || [];
                const lowerSiblings = siblings
                    .map(id => nodeLookup.get(id))
                    .filter(node => node && node.position.y > currentNode.position.y)
                    .sort((a, b) => a!.position.y - b!.position.y);

                if (lowerSiblings.length > 0) {
                    return lowerSiblings[0]!.id;
                }
                break;
            }
        }

        return null;
    }, [selectedNodeId, store]);

    // Tab 键添加子节点
    useHotkeys('tab', (e) => {
        e.preventDefault();
        if (selectedNodeId) addChildNode(selectedNodeId);
    }, { enableOnFormTags: true, preventDefault: true });

    // Enter 键添加同级节点
    useHotkeys('enter', (e) => {
        e.preventDefault();
        if (selectedNodeId) addSiblingNode(selectedNodeId);
    }, { enableOnFormTags: true, preventDefault: true });

    // 撤销重做
    // useHotkeys('ctrl+z, cmd+z', (e) => {

    //     undo();
    // }, { enableOnFormTags: false });

    // useHotkeys('ctrl+y, cmd+y', (e) => {

    //     redo();
    // }, { enableOnFormTags: false });

    // 方向键导航
    const directions = ['left', 'right', 'up', 'down'] as const;
    directions.forEach(direction => {
        useHotkeys(direction, (e) => {
            e.preventDefault();
            const nextNodeId = getNextNodeInDirection(direction);
            if (nextNodeId) setSelectedNodeId(nextNodeId);
        }, { enableOnFormTags: true });
    });
}