import { useState, useRef, useEffect } from 'react';
import { Node, Edge } from '@xyflow/react';
import { debounce } from 'lodash';
import { useSelector, useDispatch } from 'react-redux';
import { updateCanvasDataMap } from '@/store/ideContainer';

import { Dispatch } from 'redux';

export const useFlowEditorState = (initialData?: any) => {
  const [nodes, setNodes] = useState<Node[]>([]);
  const [edges, setEdges] = useState<Edge[]>([]);
  const { canvasDataMap, nodeStatusMap, isRunning, appRuntimeData, currentAppData } = useSelector((state: any) => state.ideContainer);
  const dispatch = useDispatch();

  // 辅助函数：获取当前应用/子流程的唯一标识符
  const getCurrentAppKey = (currentAppData: any) => {
    if (!currentAppData) return null;
    // 如果是子流程（key包含'sub'），使用key作为标识符
    if (currentAppData.key && currentAppData.key.includes('sub')) {
      return currentAppData.key;
    }
    // 否则使用id
    return currentAppData.id;
  };

  // 获取当前应用的运行状态
  const currentAppKey = getCurrentAppKey(currentAppData);
  const currentAppIsRunning = currentAppKey && appRuntimeData[currentAppKey]
    ? appRuntimeData[currentAppKey].isRunning
    : false;

  // 添加编辑弹窗相关状态
  const [editingNode, setEditingNode] = useState<Node | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isDelete, setIsDelete] = useState(false);

  // 添加节点选择弹窗状态
  const [edgeForNodeAdd, setEdgeForNodeAdd] = useState<Edge | null>(null);
  const [positionForNodeAdd, setPositionForNodeAdd] = useState<{ x: number, y: number } | null>(null);

  // 在组件顶部添加历史记录相关状态
  const [historyInitialized, setHistoryInitialized] = useState(false);
  const historyTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // 更新节点状态，将从store获取的状态应用到节点上
  useEffect(() => {
    setNodes(prevNodes => 
      prevNodes.map(node => ({
        ...node,
        data: {
          ...node.data,
          status: nodeStatusMap[node.id] || 'waiting',
          isStatusVisible: currentAppIsRunning // 只有在运行时才显示状态指示器
        }
      }))
    );
  }, [nodeStatusMap, currentAppIsRunning]);

  const updateCanvasDataMapDebounced = useRef(
    debounce((dispatch: Dispatch<any>, canvasDataMap: any, id: string, nodes: Node[], edges: Edge[]) => {
      dispatch(updateCanvasDataMap({
        ...canvasDataMap,
        [id]: { nodes, edges }
      }));
    }, 500)
  ).current;

  return {
    // State values
    nodes,
    setNodes,
    edges,
    setEdges,
    canvasDataMap,
    editingNode,
    setEditingNode,
    isEditModalOpen,
    setIsEditModalOpen,
    isDelete,
    setIsDelete,
    edgeForNodeAdd,
    setEdgeForNodeAdd,
    positionForNodeAdd,
    setPositionForNodeAdd,
    isRunning: currentAppIsRunning, // 使用当前应用的运行状态
    historyInitialized,
    setHistoryInitialized,
    historyTimeoutRef,
    updateCanvasDataMapDebounced,
    
    // Redux
    dispatch,
    
    // Initial data
    initialData: initialData
  };
};