import { useCallback, useState } from 'react';
import { message } from 'antd';
import * as definitionService from '../../Definition/service';
import type { FlowNode, FlowEdge } from '../types';
import type { WorkflowDefinition } from '../../Definition/types';
import { NODE_DEFINITIONS, NodeType, getNodeCategory } from '../nodes';

interface LoadedWorkflowData {
    nodes: FlowNode[];
    edges: FlowEdge[];
    definition: WorkflowDefinition | null;
}

export const useWorkflowLoad = () => {
    const [loading, setLoading] = useState(false);
    const [workflowDefinition, setWorkflowDefinition] = useState<WorkflowDefinition | null>(null);

    // 获取已注册的节点类型
    const getRegisteredNodeTypes = useCallback((): NodeType[] => {
        return NODE_DEFINITIONS.map(def => def.nodeType);
    }, []);

    // 从后端数据转换为React Flow格式
    const convertToFlowFormat = useCallback((definition: WorkflowDefinition): LoadedWorkflowData => {
        const registeredTypes = getRegisteredNodeTypes();
        
        const nodes: FlowNode[] = (definition.graph?.nodes || [])
            .filter(node => {
                // 过滤掉不支持的节点类型
                const isSupported = registeredTypes.includes(node.nodeType as any);
                if (!isSupported) {
                    console.warn(`节点类型 "${node.nodeType}" 不支持，已跳过`, node);
                }
                return isSupported;
            })
            .map(node => {
                // 根据nodeType查找对应的节点定义
                const nodeDefinition = NODE_DEFINITIONS.find(def => def.nodeType === node.nodeType);
                
                // ✅ 使用节点定义中的配置，避免硬编码
                const icon = nodeDefinition?.renderConfig.icon.content || '❓';
                const color = nodeDefinition?.renderConfig.theme.primary || '#6b7280';
                const category = nodeDefinition?.category || getNodeCategory(node.nodeType) as any;
                
                return {
                    id: node.id.toString(),
                    type: node.nodeType,
                    position: node.position || { x: 100, y: 100 },
                    data: {
                        label: node.nodeName,
                        nodeType: node.nodeType as any,
                        category,
                        icon,
                        color,
                        configs: node.configs || {},
                        inputMapping: node.inputMapping || {},
                        outputs: node.outputs || [],  // ✅ 从后端加载的输出能力定义
                        // 添加节点定义引用，用于配置弹窗
                        nodeDefinition
                    },
                    selected: false,
                    dragging: false
                };
            });

        // 创建节点ID集合（用于过滤边）
        const nodeIds = new Set(nodes.map(n => n.id));
        
        const edges: FlowEdge[] = (definition.graph?.edges || [])
            .filter(edge => {
                // 只保留两端节点都存在的边
                const sourceExists = nodeIds.has(edge.from);
                const targetExists = nodeIds.has(edge.to);
                if (!sourceExists || !targetExists) {
                    console.warn(`边的节点不存在，已跳过:`, edge);
                }
                return sourceExists && targetExists;
            })
            .map(edge => {
                const edgeConfig: any = edge.config || {};
                const condition = edgeConfig.condition || { type: 'DEFAULT', priority: 10 };
                const label = condition.expression || edge.name || '';
                
                return {
                    id: edge.id,
                    source: edge.from,                    // 后端使用from字段作为source
                    target: edge.to,                      // 后端使用to字段作为target
                    type: 'smoothstep',
                    animated: true,
                    style: {
                        stroke: '#94a3b8',
                        strokeWidth: 2,
                    },
                    markerEnd: {
                        type: 'arrowclosed' as const,
                        color: '#94a3b8',
                    },
                    label,
                    data: {
                        label,
                        condition
                    }
                };
            });

        return {
            nodes,
            edges,
            definition
        };
    }, []);

    // ✅ 已删除硬编码的 getNodeIcon 和 getNodeColor 函数
    // 现在直接从节点定义的 renderConfig 中获取图标和颜色

    // 加载工作流定义
    const loadWorkflow = useCallback(async (workflowId: number): Promise<LoadedWorkflowData | null> => {
        setLoading(true);
        
        try {
            const definition = await definitionService.getDefinitionDetail(workflowId);
            setWorkflowDefinition(definition);
            
            const flowData = convertToFlowFormat(definition);
            
            // 提示不支持的节点
            const totalNodes = definition.graph?.nodes?.length || 0;
            const loadedNodes = flowData.nodes.length;
            if (totalNodes > loadedNodes) {
                message.warning(`工作流加载成功，但有 ${totalNodes - loadedNodes} 个节点类型不支持，已跳过`);
            } else {
                message.success(`工作流 "${definition.name}" 加载成功`);
            }
            
            return flowData;
        } catch (error) {
            console.error('加载工作流失败:', error);
            message.error('加载工作流失败');
            return null;
        } finally {
            setLoading(false);
        }
    }, [convertToFlowFormat]);

    // 重置加载状态
    const resetLoad = useCallback(() => {
        setWorkflowDefinition(null);
        setLoading(false);
    }, []);

    return {
        loading,
        workflowDefinition,
        loadWorkflow,
        resetLoad
    };
};
