import { useState, useCallback } from 'react';
import { Edge } from '@xyflow/react';
import { AppNodeType } from '../types/node';
import { useCanvasStore } from '@/lib/store/canvasStore';

interface HistoryState {
    nodes: AppNodeType[];
    edges: Edge[];
}

/**
 * @deprecated 已弃用 - 使用 canvasStore 的增量历史系统
 * 
 * 这个 hook 现在只是一个包装器，将所有操作重定向到 canvasStore 的增量历史系统。
 * 保留此 hook 是为了向后兼容，新代码应直接使用 canvasStore：
 * 
 * ```tsx
 * const { undo, redo, canUndo, canRedo, saveHistory } = useCanvasStore();
 * ```
 * 
 * 原始实现使用 snapshot-based 历史，已被 canvasStore 的 IncrementalHistory 取代。
 */
export const useHistory = (
    setNodes: (nodes: AppNodeType[]) => void,
    setEdges: (edges: Edge[]) => void
) => {
    // 从 canvasStore 获取统一的撤销/重做功能
    const canvasUndo = useCanvasStore((state) => state.undo);
    const canvasRedo = useCanvasStore((state) => state.redo);
    const canvasCanUndo = useCanvasStore((state) => state.canUndo);
    const canvasCanRedo = useCanvasStore((state) => state.canRedo);
    const canvasSaveHistory = useCanvasStore((state) => state.saveHistory);

    // 为了向后兼容，保持相同的接口
    const takeSnapshot = useCallback((nodes: AppNodeType[], edges: Edge[]) => {
        // 新的增量历史系统自动处理快照
        // 只需确保 canvasStore 中的状态已更新
        canvasSaveHistory();
    }, [canvasSaveHistory]);

    const undo = useCallback((currentNodes: AppNodeType[], currentEdges: Edge[]) => {
        canvasUndo();
        // 状态已由 canvasStore 更新，但为了兼容旧接口，需要调用 setNodes/setEdges
        // 实际上 canvasStore 已经更新了 nodes/edges，这里不需要做什么
    }, [canvasUndo]);

    const redo = useCallback((currentNodes: AppNodeType[], currentEdges: Edge[]) => {
        canvasRedo();
        // 同上
    }, [canvasRedo]);

    // 从 canvasStore 获取实际的状态
    const canUndo = canvasCanUndo();
    const canRedo = canvasCanRedo();

    if (process.env.NODE_ENV === 'development') {
        console.warn('[useHistory] 已弃用，请迁移到 useCanvasStore: const { undo, redo, canUndo, canRedo } = useCanvasStore()');
    }

    return { 
        takeSnapshot, 
        undo, 
        redo, 
        canUndo, 
        canRedo 
    };
};
