import { useState, useRef } 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 } = useSelector((state: any) => state.ideContainer);
  const dispatch = useDispatch();

  // 添加编辑弹窗相关状态
  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 [isRunning, setIsRunning] = useState(false);

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

  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,
    setIsRunning,
    historyInitialized,
    setHistoryInitialized,
    historyTimeoutRef,
    updateCanvasDataMapDebounced,
    
    // Redux
    dispatch,
    
    // Initial data
    initialData: initialData
  };
};