import React, { useMemo } from 'react';
import { ReactFlow, Background, Controls, MiniMap, Node, Edge, Handle, Position, BackgroundVariant } from '@xyflow/react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import dayjs from 'dayjs';
import '@xyflow/react/dist/style.css';
import { WorkflowHistoricalInstance, WorkflowInstanceStage } from '../../types';
import { NodeType } from '../../../../Design/nodes/types';

interface FlowGraphTabProps {
    instanceData: WorkflowHistoricalInstance;
    getStatusBadge: (status: string) => React.ReactNode;
    getNodeTypeText: (nodeType: string) => string;
}

// 自定义节点组件 - 增强版
const EnhancedCustomNode: React.FC<any> = ({ data, selected }) => {
    const nodeType = data.nodeType as NodeType;
    const status = data.status;
    
    // 根据状态判断是否需要虚线边框
    const isNotStarted = status === 'NOT_STARTED';
    
    return (
        <div className="relative group">
            {/* 输入连接点 */}
            {nodeType !== NodeType.START_EVENT && (
                <Handle
                    type="target"
                    position={Position.Left}
                    className="!w-3 !h-3 !rounded-full !border-2 !border-white !shadow-md transition-transform hover:!scale-125"
                    style={{ background: data.handleColor || '#1890ff' }}
                />
            )}
            
            {/* 节点内容 */}
            <Card 
                className={`
                    min-w-[140px] max-w-[240px] transition-all duration-200
                    ${selected ? 'ring-2 ring-primary ring-offset-2' : ''}
                    ${isNotStarted ? 'border-dashed border-2' : 'shadow-md'}
                    hover:shadow-xl hover:scale-105
                `}
                style={{
                    background: data.background,
                    color: data.textColor,
                    borderColor: data.borderColor,
                }}
            >
                <CardContent className="p-3">
                    {data.label}
                </CardContent>
            </Card>
            
            {/* 输出连接点 */}
            {nodeType !== NodeType.END_EVENT && (
                <Handle
                    type="source"
                    position={Position.Right}
                    className="!w-3 !h-3 !rounded-full !border-2 !border-white !shadow-md transition-transform hover:!scale-125"
                    style={{ background: data.handleColor || '#1890ff' }}
                />
            )}
        </div>
    );
};

const nodeTypes = {
    enhanced: EnhancedCustomNode
};

const FlowGraphTab: React.FC<FlowGraphTabProps> = ({ 
    instanceData, 
    getStatusBadge,
    getNodeTypeText 
}) => {
    // 构建节点状态映射
    const nodeStatusMap = useMemo(() => {
        const map = new Map<string, WorkflowInstanceStage>();
        instanceData.stages.forEach(stage => {
            map.set(stage.nodeId, stage);
        });
        return map;
    }, [instanceData.stages]);

    // 获取节点状态
    const getNodeStatus = (nodeId: string): string => {
        const stage = nodeStatusMap.get(nodeId);
        return stage?.status || 'NOT_STARTED';
    };

    // 获取节点颜色
    const getNodeColor = (status: string) => {
        const colorMap: Record<string, { bg: string; border: string; text: string }> = {
            COMPLETED: { 
                bg: 'linear-gradient(135deg, #52c41a 0%, #73d13d 100%)', 
                border: '#52c41a',
                text: '#fff'
            },
            RUNNING: { 
                bg: 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)', 
                border: '#1890ff',
                text: '#fff'
            },
            FAILED: { 
                bg: 'linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%)', 
                border: '#ff4d4f',
                text: '#fff'
            },
            TERMINATED: { 
                bg: 'linear-gradient(135deg, #faad14 0%, #ffc53d 100%)', 
                border: '#faad14',
                text: '#fff'
            },
            NOT_STARTED: { 
                bg: '#fafafa', 
                border: '#d9d9d9',
                text: '#666'
            }
        };
        return colorMap[status] || colorMap.NOT_STARTED;
    };

    // 转换为React Flow节点
    const flowNodes: Node[] = useMemo(() => {
        if (!instanceData.graph?.nodes) return [];

        return instanceData.graph.nodes.map(node => {
            const status = getNodeStatus(node.id);
            const stage = nodeStatusMap.get(node.id);
            const colors = getNodeColor(status);

            return {
                id: node.id,
                type: 'enhanced',
                position: { x: node.position.x, y: node.position.y },
                data: {
                    nodeType: node.nodeType,
                    status: status,
                    handleColor: colors.border,
                    background: colors.bg,
                    borderColor: colors.border,
                    textColor: colors.text,
                    label: (
                        <div className="space-y-2">
                            <div className="font-semibold text-sm">
                                {node.nodeName}
                            </div>
                            <div className="text-xs opacity-80">
                                {getNodeTypeText(node.nodeType)}
                            </div>
                            {stage && (
                                <div className="flex justify-center">
                                    {getStatusBadge(status)}
                                </div>
                            )}
                            {stage?.startTime && (
                                <div className="text-xs opacity-70 mt-1">
                                    {dayjs(stage.startTime).format('HH:mm:ss')}
                                </div>
                            )}
                        </div>
                    )
                }
            };
        });
    }, [instanceData.graph, nodeStatusMap]);

    // 判断连线是否已执行
    const isEdgeExecuted = (fromNodeId: string): boolean => {
        const fromStage = nodeStatusMap.get(fromNodeId);
        return fromStage?.status === 'COMPLETED' || fromStage?.status === 'RUNNING';
    };

    // 转换为React Flow边
    const flowEdges: Edge[] = useMemo(() => {
        if (!instanceData.graph?.edges) return [];

        return instanceData.graph.edges.map(edge => {
            const executed = isEdgeExecuted(edge.from);
            const fromStatus = getNodeStatus(edge.from);
            const toStatus = getNodeStatus(edge.to);
            
            // 判断是否应该使用虚线
            const isDashed = !executed || toStatus === 'NOT_STARTED';
            
            return {
                id: edge.id,
                source: edge.from,
                target: edge.to,
                sourceHandle: edge.sourceHandle,
                targetHandle: edge.targetHandle,
                label: edge.name || undefined,
                type: 'smoothstep',
                animated: executed && toStatus === 'RUNNING',
                style: {
                    stroke: executed ? '#52c41a' : '#d9d9d9',
                    strokeWidth: executed ? 3 : 2,
                    strokeDasharray: isDashed ? '5,5' : undefined,  // 虚线效果
                },
                markerEnd: {
                    type: 'arrowclosed' as const,
                    color: executed ? '#52c41a' : '#d9d9d9',
                },
                labelStyle: {
                    fontSize: 11,
                    fontWeight: 500,
                    fill: executed ? '#52c41a' : '#999',
                },
                labelBgStyle: {
                    fill: '#fff',
                    fillOpacity: 0.9,
                }
            };
        });
    }, [instanceData.graph, nodeStatusMap]);

    return (
        <div className="space-y-4">
            {/* 基本信息卡片 */}
            <Card>
                <CardContent className="pt-6">
                    <div className="grid grid-cols-2 gap-4">
                        <div className="flex items-start py-2">
                            <div className="w-24 text-sm font-medium text-muted-foreground flex-shrink-0">业务标识</div>
                            <div className="flex-1 text-sm font-mono">{instanceData.businessKey}</div>
                        </div>
                        <div className="flex items-start py-2">
                            <div className="w-24 text-sm font-medium text-muted-foreground flex-shrink-0">状态</div>
                            <div className="flex-1">{getStatusBadge(instanceData.status)}</div>
                        </div>
                        <div className="flex items-start py-2">
                            <div className="w-24 text-sm font-medium text-muted-foreground flex-shrink-0">开始时间</div>
                            <div className="flex-1 text-sm">{dayjs(instanceData.startTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                        </div>
                        <div className="flex items-start py-2">
                            <div className="w-24 text-sm font-medium text-muted-foreground flex-shrink-0">结束时间</div>
                            <div className="flex-1 text-sm">
                                {instanceData.endTime ? dayjs(instanceData.endTime).format('YYYY-MM-DD HH:mm:ss') : '进行中...'}
                            </div>
                        </div>
                    </div>
                </CardContent>
            </Card>

            {/* 流程图卡片 */}
            {instanceData.graph ? (
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center justify-between">
                            <span>流程执行图</span>
                            <span className="text-sm font-normal text-muted-foreground">
                                实时展示流程执行状态
                            </span>
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="rounded-lg border-2 border-border overflow-hidden" style={{ height: '500px' }}>
                            <ReactFlow
                                nodes={flowNodes}
                                edges={flowEdges}
                                nodeTypes={nodeTypes}
                                fitView
                                minZoom={0.3}
                                maxZoom={2}
                                defaultViewport={{ x: 0, y: 0, zoom: 0.8 }}
                                attributionPosition="bottom-right"
                            >
                                <Background 
                                    variant={BackgroundVariant.Dots} 
                                    gap={16} 
                                    size={1} 
                                    color="#e0e0e0"
                                />
                                <Controls 
                                    showInteractive={false}
                                    className="!shadow-lg !border !border-border"
                                />
                                <MiniMap 
                                    nodeColor={(node: Node) => {
                                        const status = getNodeStatus(node.id);
                                        const colors = getNodeColor(status);
                                        return colors.border;
                                    }}
                                    className="!shadow-lg !border !border-border"
                                    maskColor="rgba(0, 0, 0, 0.05)"
                                />
                            </ReactFlow>
                        </div>
                        
                        {/* 图例 */}
                        <div className="mt-4 flex flex-wrap gap-4 justify-center text-sm">
                            <div className="flex items-center gap-2">
                                <div className="w-4 h-4 bg-gradient-to-br from-green-500 to-green-400 rounded shadow-sm" />
                                <span>已完成</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <div className="w-4 h-4 bg-gradient-to-br from-blue-500 to-blue-400 rounded shadow-sm animate-pulse" />
                                <span>运行中</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <div className="w-4 h-4 bg-gradient-to-br from-red-500 to-red-400 rounded shadow-sm" />
                                <span>失败</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <div className="w-4 h-4 bg-gray-200 border-2 border-dashed border-gray-400 rounded" />
                                <span>未执行</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <div className="w-12 h-0.5 bg-green-500" />
                                <span>已执行路径</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <div className="w-12 h-0.5 border-t-2 border-dashed border-gray-400" />
                                <span>未执行路径</span>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            ) : (
                <Card>
                    <CardContent className="pt-6">
                        <div className="text-center py-10 text-muted-foreground">
                            暂无流程图数据
                        </div>
                    </CardContent>
                </Card>
            )}
        </div>
    );
};

export default FlowGraphTab;

