import { useState, useCallback, useRef } from 'react';
import type { FlowNode, FlowEdge } from '../types';

/**
 * 历史记录项
 */
interface HistoryState {
    nodes: FlowNode[];
    edges: FlowEdge[];
}

/**
 * 历史记录管理Hook
 * 实现撤销/重做功能
 */
export const useHistory = () => {
    const [history, setHistory] = useState<HistoryState[]>([]);
    const [currentIndex, setCurrentIndex] = useState(-1);
    const isRecording = useRef(true);

    /**
     * 记录当前状态到历史
     */
    const record = useCallback((nodes: FlowNode[], edges: FlowEdge[]) => {
        if (!isRecording.current) return;

        setHistory(prev => {
            // 移除当前索引之后的所有历史
            const newHistory = prev.slice(0, currentIndex + 1);
            // 添加新状态
            newHistory.push({
                nodes: JSON.parse(JSON.stringify(nodes)),
                edges: JSON.parse(JSON.stringify(edges))
            });
            // 限制历史记录数量（最多50条）
            if (newHistory.length > 50) {
                newHistory.shift();
                setCurrentIndex(prev => prev);
            } else {
                setCurrentIndex(newHistory.length - 1);
            }
            return newHistory;
        });
    }, [currentIndex]);

    /**
     * 撤销
     */
    const undo = useCallback((): HistoryState | null => {
        if (currentIndex <= 0) {
            return null;
        }
        const newIndex = currentIndex - 1;
        setCurrentIndex(newIndex);
        return history[newIndex];
    }, [currentIndex, history]);

    /**
     * 重做
     */
    const redo = useCallback((): HistoryState | null => {
        if (currentIndex >= history.length - 1) {
            return null;
        }
        const newIndex = currentIndex + 1;
        setCurrentIndex(newIndex);
        return history[newIndex];
    }, [currentIndex, history]);

    /**
     * 是否可以撤销
     */
    const canUndo = useCallback(() => {
        return currentIndex > 0;
    }, [currentIndex]);

    /**
     * 是否可以重做
     */
    const canRedo = useCallback(() => {
        return currentIndex < history.length - 1;
    }, [currentIndex, history.length]);

    /**
     * 暂停记录（用于批量操作时）
     */
    const pauseRecording = useCallback(() => {
        isRecording.current = false;
    }, []);

    /**
     * 恢复记录
     */
    const resumeRecording = useCallback(() => {
        isRecording.current = true;
    }, []);

    /**
     * 清空历史
     */
    const clear = useCallback(() => {
        setHistory([]);
        setCurrentIndex(-1);
    }, []);

    return {
        record,
        undo,
        redo,
        canUndo: canUndo(),
        canRedo: canRedo(),
        pauseRecording,
        resumeRecording,
        clear
    };
};

