import { create } from 'zustand';
import { Node, Edge, Connection, addEdge, applyNodeChanges, applyEdgeChanges } from 'reactflow';
import { NodeType, ProcessingStatus, DataFlow } from '../types/canvas';

interface CanvasState {
  nodes: Node[];
  edges: Edge[];
  selectedNodes: string[];
  viewport: { x: number; y: number; zoom: number };
  showNodeSelector: boolean;
  nodeSelectorPosition: { x: number; y: number };
  processingNodes: Map<string, ProcessingInfo>;
}

interface ProcessingInfo {
  status: ProcessingStatus;
  progress: number;
  startTime: number;
  estimatedTime?: number;
  error?: string;
}

interface CanvasActions {
  // 节点操作
  addNode: (node: Node) => void;
  updateNode: (nodeId: string, updates: Partial<Node>) => void;
  deleteNode: (nodeId: string) => void;
  setNodes: (nodes: Node[]) => void;
  onNodesChange: (changes: any[]) => void;
  
  // 连线操作
  addEdge: (edge: Edge) => void;
  deleteEdge: (edgeId: string) => void;
  setEdges: (edges: Edge[]) => void;
  onEdgesChange: (changes: any[]) => void;
  onConnect: (connection: Connection) => void;
  
  // 选择操作
  setSelectedNodes: (nodeIds: string[]) => void;
  clearSelection: () => void;
  
  // 视图操作
  setViewport: (viewport: { x: number; y: number; zoom: number }) => void;
  
  // 节点选择器
  showNodeSelectorAt: (position: { x: number; y: number }) => void;
  hideNodeSelector: () => void;
  
  // 处理状态
  startProcessing: (nodeId: string) => void;
  updateProgress: (nodeId: string, progress: number) => void;
  completeProcessing: (nodeId: string, result: any) => void;
  errorProcessing: (nodeId: string, error: string) => void;
  cancelProcessing: (nodeId: string) => void;
  
  // 画布操作
  clearCanvas: () => void;
  resetCanvas: () => void;

  // 获取活动处理
  getActiveProcesses: () => string[];
}

export const useCanvasStore = create<CanvasState & CanvasActions>((set, get) => ({
  // 初始状态
  nodes: [],
  edges: [],
  selectedNodes: [],
  viewport: { x: 0, y: 0, zoom: 1 },
  showNodeSelector: false,
  nodeSelectorPosition: { x: 0, y: 0 },
  processingNodes: new Map(),

  // 节点操作
  addNode: (node: Node) => set(state => ({
    nodes: [...state.nodes, node]
  })),

  updateNode: (nodeId: string, updates: Partial<Node>) => set(state => ({
    nodes: state.nodes.map(node => 
      node.id === nodeId ? { ...node, ...updates } : node
    )
  })),

  deleteNode: (nodeId: string) => set(state => ({
    nodes: state.nodes.filter(node => node.id !== nodeId),
    edges: state.edges.filter(edge => 
      edge.source !== nodeId && edge.target !== nodeId
    )
  })),

  setNodes: (nodes: Node[]) => set({ nodes }),

  onNodesChange: (changes: any[]) => set(state => ({
    nodes: applyNodeChanges(changes, state.nodes)
  })),

  // 连线操作
  addEdge: (edge: Edge) => set(state => ({
    edges: [...state.edges, edge]
  })),

  deleteEdge: (edgeId: string) => set(state => ({
    edges: state.edges.filter(edge => edge.id !== edgeId)
  })),

  setEdges: (edges: Edge[]) => set({ edges }),

  onEdgesChange: (changes: any[]) => set(state => ({
    edges: applyEdgeChanges(changes, state.edges)
  })),

  onConnect: (connection: Connection) => set(state => {
    const newEdge = {
      ...connection,
      id: `edge-${connection.source}-${connection.target}`,
      animated: true,
      style: { strokeWidth: 2 }
    };
    return {
      edges: addEdge(newEdge, state.edges)
    };
  }),

  // 选择操作
  setSelectedNodes: (nodeIds: string[]) => set({ selectedNodes: nodeIds }),
  clearSelection: () => set({ selectedNodes: [] }),

  // 视图操作
  setViewport: (viewport: { x: number; y: number; zoom: number }) => set({ viewport }),

  // 节点选择器
  showNodeSelectorAt: (position: { x: number; y: number }) => set({
    showNodeSelector: true,
    nodeSelectorPosition: position
  }),

  hideNodeSelector: () => set({ showNodeSelector: false }),

  // 处理状态
  startProcessing: (nodeId: string) => set(state => ({
    processingNodes: new Map(state.processingNodes.set(nodeId, {
      status: 'loading',
      progress: 0,
      startTime: Date.now()
    }))
  })),

  updateProgress: (nodeId: string, progress: number) => set(state => {
    const current = state.processingNodes.get(nodeId);
    if (current) {
      return {
        processingNodes: new Map(state.processingNodes.set(nodeId, {
          ...current,
          progress
        }))
      };
    }
    return state;
  }),

  completeProcessing: (nodeId: string, result: any) => set(state => {
    const current = state.processingNodes.get(nodeId);
    if (current) {
      // 更新节点数据
      const updatedNodes = state.nodes.map(node => 
        node.id === nodeId ? { ...node, data: { ...node.data, result } } : node
      );
      
      return {
        nodes: updatedNodes,
        processingNodes: new Map(state.processingNodes.set(nodeId, {
          ...current,
          status: 'success',
          progress: 100
        }))
      };
    }
    return state;
  }),

  errorProcessing: (nodeId: string, error: string) => set(state => {
    const current = state.processingNodes.get(nodeId);
    if (current) {
      return {
        processingNodes: new Map(state.processingNodes.set(nodeId, {
          ...current,
          status: 'error',
          error
        }))
      };
    }
    return state;
  }),

  cancelProcessing: (nodeId: string) => set(state => {
    const newMap = new Map(state.processingNodes);
    newMap.delete(nodeId);
    return { processingNodes: newMap };
  }),

  // 画布操作
  clearCanvas: () => set({
    nodes: [],
    edges: [],
    selectedNodes: [],
    processingNodes: new Map()
  }),

  resetCanvas: () => set({
    nodes: [],
    edges: [],
    selectedNodes: [],
    viewport: { x: 0, y: 0, zoom: 1 },
    showNodeSelector: false,
    processingNodes: new Map()
  }),

  // 获取活动处理
  getActiveProcesses: () => {
    const state = get();
    return Array.from(state.processingNodes.keys()).filter(nodeId => {
      const info = state.processingNodes.get(nodeId);
      return info?.status === 'loading';
    });
  }
}));
