import React, { useMemo } from 'react';
import { Dialog, DialogPortal, DialogOverlay, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { WorkflowHistoricalInstance, WorkflowInstanceStage } from '../types';
import ReactFlow, { Background, Controls, MiniMap, Node, Edge } from 'reactflow';
import dayjs from 'dayjs';
import 'reactflow/dist/style.css';
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X, Clock, CheckCircle2, XCircle, AlertCircle } from "lucide-react";
import { cn } from "@/lib/utils";

interface DetailModalProps {
    visible: boolean;
    onCancel: () => void;
    instanceData?: WorkflowHistoricalInstance;
}

const DetailModal: React.FC<DetailModalProps> = ({ visible, onCancel, instanceData }) => {
    if (!instanceData) return null;

    const getStatusBadge = (status: string) => {
        const statusMap: Record<string, { variant: 'default' | 'secondary' | 'destructive' | 'outline' | 'success'; text: string }> = {
            COMPLETED: { variant: 'success', text: '已完成' },
            RUNNING: { variant: 'default', text: '运行中' },
            FAILED: { variant: 'destructive', text: '失败' },
            TERMINATED: { variant: 'secondary', text: '已终止' },
            NOT_STARTED: { variant: 'outline', text: '未执行' }
        };
        const statusInfo = statusMap[status] || { variant: 'outline', text: status };
        return <Badge variant={statusInfo.variant}>{statusInfo.text}</Badge>;
    };

    const getNodeTypeText = (nodeType: string) => {
        const nodeTypeMap: Record<string, string> = {
            START_EVENT: '开始节点',
            END_EVENT: '结束节点',
            SERVICE_TASK: '服务任务',
            USER_TASK: '用户任务',
            SCRIPT_TASK: '脚本任务',
            NOTIFICATION: '通知任务',
            JENKINS_BUILD: 'Jenkins构建',
            APPROVAL: '审批任务',
            StartEvent: '开始节点',
            EndEvent: '结束节点',
            ServiceTask: '服务任务',
            UserTask: '用户任务',
            ScriptTask: '脚本任务'
        };
        return nodeTypeMap[nodeType] || nodeType;
    };

    const getStatusIcon = (status: string) => {
        switch (status) {
            case 'COMPLETED':
                return <CheckCircle2 className="h-4 w-4 text-green-500" />;
            case 'RUNNING':
                return <Clock className="h-4 w-4 text-blue-500 animate-pulse" />;
            case 'FAILED':
                return <XCircle className="h-4 w-4 text-red-500" />;
            default:
                return <AlertCircle className="h-4 w-4 text-gray-400" />;
        }
    };

    // 构建节点状态映射
    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, string> = {
            COMPLETED: '#52c41a',
            RUNNING: '#1890ff',
            FAILED: '#ff4d4f',
            TERMINATED: '#faad14',
            NOT_STARTED: '#d9d9d9'
        };
        return colorMap[status] || '#d9d9d9';
    };

    // 转换为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);

            return {
                id: node.id,
                type: 'default',
                position: { x: node.position.x + 400, y: node.position.y + 200 },
                data: {
                    label: (
                        <div style={{ textAlign: 'center', minWidth: '80px' }}>
                            <div style={{ 
                                fontSize: '12px', 
                                fontWeight: 500,
                                marginBottom: '4px'
                            }}>
                                {node.nodeName}
                            </div>
                            <div style={{ fontSize: '10px', color: '#666' }}>
                                {getNodeTypeText(node.nodeType)}
                            </div>
                            {stage && (
                                <div style={{ fontSize: '10px', marginTop: '4px' }}>
                                    {getStatusBadge(status)}
                                </div>
                            )}
                        </div>
                    )
                },
                style: {
                    background: getNodeColor(status),
                    color: status === 'NOT_STARTED' ? '#333' : '#fff',
                    border: `2px solid ${getNodeColor(status)}`,
                    borderRadius: '8px',
                    padding: '10px',
                    minWidth: '120px',
                    boxShadow: status === 'RUNNING' ? '0 0 10px rgba(24, 144, 255, 0.5)' : undefined
                }
            };
        });
    }, [instanceData.graph, nodeStatusMap]);

    // 判断连线是否已执行
    const isEdgeExecuted = (fromNodeId: string, _toNodeId: 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, edge.to);
            
            return {
                id: edge.id,
                source: edge.from,
                target: edge.to,
                label: edge.name || undefined,
                type: 'smoothstep',
                animated: isEdgeExecuted(edge.from, edge.to) && getNodeStatus(edge.to) === 'RUNNING',
                style: {
                    stroke: executed ? '#52c41a' : '#d9d9d9',
                    strokeWidth: 2
                },
                labelStyle: {
                    fontSize: 10,
                    fill: '#666'
                }
            };
        });
    }, [instanceData.graph, nodeStatusMap]);

    // 描述信息组件
    const DescriptionItem = ({ label, value }: { label: string; value: React.ReactNode }) => (
        <div className="flex items-start py-2 border-b last:border-b-0">
            <div className="w-32 text-sm font-medium text-muted-foreground flex-shrink-0">{label}</div>
            <div className="flex-1 text-sm">{value}</div>
        </div>
    );

    return (
        <Dialog open={visible} onOpenChange={(open) => !open && onCancel()}>
            <DialogPortal>
                <DialogOverlay className="z-[60]" />
                <DialogPrimitive.Content
                    className={cn(
                        "fixed left-[50%] top-[50%] z-[60] grid w-full max-w-7xl translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg max-h-[90vh] overflow-y-auto"
                    )}
                >
                    <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
                        <X className="h-4 w-4" />
                        <span className="sr-only">Close</span>
                    </DialogPrimitive.Close>
                    <DialogHeader>
                        <DialogTitle>流程执行详情</DialogTitle>
                    </DialogHeader>
                    
                    <Tabs defaultValue="graph" className="w-full">
                        <TabsList className="grid w-full grid-cols-3">
                            <TabsTrigger value="graph">流程图</TabsTrigger>
                            <TabsTrigger value="timeline">执行时间线</TabsTrigger>
                            <TabsTrigger value="info">详细信息</TabsTrigger>
                        </TabsList>

                        {/* 流程图标签页 */}
                        <TabsContent value="graph" className="space-y-4">
                            <Card>
                                <CardContent className="pt-6">
                                    <div className="grid grid-cols-2 gap-4">
                                        <DescriptionItem label="业务标识" value={instanceData.businessKey} />
                                        <DescriptionItem label="状态" value={getStatusBadge(instanceData.status)} />
                                        <DescriptionItem 
                                            label="开始时间" 
                                            value={dayjs(instanceData.startTime).format('YYYY-MM-DD HH:mm:ss')} 
                                        />
                                        <DescriptionItem 
                                            label="结束时间" 
                                            value={instanceData.endTime ? dayjs(instanceData.endTime).format('YYYY-MM-DD HH:mm:ss') : '暂无'} 
                                        />
                                    </div>
                                </CardContent>
            </Card>

                            {instanceData.graph ? (
                                <Card>
                                    <CardHeader>
                                        <CardTitle>流程执行图</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div style={{ height: '400px', border: '1px solid hsl(var(--border))', borderRadius: '8px' }}>
                                            <ReactFlow
                                                nodes={flowNodes}
                                                edges={flowEdges}
                                                fitView
                                                minZoom={0.5}
                                                maxZoom={1.5}
                                                defaultViewport={{ x: 0, y: 0, zoom: 0.8 }}
                                            >
                                                <Background />
                                                <Controls />
                                                <MiniMap 
                                                    nodeColor={(node: Node) => {
                                                        const status = getNodeStatus(node.id);
                                                        return getNodeColor(status);
                                                    }}
                                                />
                                            </ReactFlow>
                                        </div>
                                        <div className="mt-4 flex gap-4 justify-center text-sm">
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 bg-green-500 rounded" />
                                                <span>已完成</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 bg-blue-500 rounded" />
                                                <span>运行中</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 bg-red-500 rounded" />
                                                <span>失败</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 bg-gray-300 rounded" />
                                                <span>未执行</span>
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            ) : (
                                <Card>
                                    <CardContent className="pt-6">
                                        <div className="text-center py-10 text-muted-foreground">
                                            暂无流程图数据
                            </div>
                                    </CardContent>
            </Card>
                            )}
                        </TabsContent>

                        {/* 执行时间线标签页 */}
                        <TabsContent value="timeline">
                            <Card>
                                <CardContent className="pt-6">
                                    <div className="relative space-y-4">
                                        {instanceData.stages.map((stage, index) => (
                                            <div key={stage.id || index} className="flex gap-4">
                                                {/* 时间线图标 */}
                                                <div className="flex flex-col items-center">
                                                    <div className="flex items-center justify-center w-8 h-8 rounded-full border-2 bg-background z-10"
                                                        style={{
                                                            borderColor: stage.status === 'COMPLETED' ? '#52c41a' : 
                                                                       stage.status === 'FAILED' ? '#ff4d4f' : 
                                                                       stage.status === 'RUNNING' ? '#1890ff' : '#d9d9d9'
                                                        }}
                                                    >
                                                        {getStatusIcon(stage.status)}
                                                    </div>
                                                    {index < instanceData.stages.length - 1 && (
                                                        <div className="w-0.5 h-full bg-border mt-1" />
                                                    )}
                                                </div>
                                                
                                                {/* 时间线内容 */}
                                                <div className="flex-1 pb-8">
                                                    <div className="font-medium mb-1 flex items-center gap-2">
                                                        {stage.nodeName}
                                                        <span className="text-xs text-muted-foreground font-normal">
                                                            {getNodeTypeText(stage.nodeType)}
                                                        </span>
                                    </div>
                                                    <div className="text-sm text-muted-foreground mb-2">
                                                        {stage.startTime && dayjs(stage.startTime).format('YYYY-MM-DD HH:mm:ss')}
                                                        {stage.endTime && ` → ${dayjs(stage.endTime).format('HH:mm:ss')}`}
                                                        {stage.startTime && stage.endTime && (
                                                            <span className="ml-2">
                                                                (耗时: {dayjs(stage.endTime).diff(dayjs(stage.startTime), 'second')}秒)
                                                            </span>
                                                        )}
                                                    </div>
                                                    <div>{getStatusBadge(stage.status)}</div>
                                                </div>
                                            </div>
                                        ))}
                            </div>
                                </CardContent>
                            </Card>
                        </TabsContent>

                        {/* 详细信息标签页 */}
                        <TabsContent value="info">
                            <Card>
                                <CardContent className="pt-6">
                                    <div className="space-y-0">
                                        <DescriptionItem label="流程实例ID" value={instanceData.processInstanceId} />
                                        <DescriptionItem label="流程定义ID" value={instanceData.processDefinitionId} />
                                        <DescriptionItem label="业务标识" value={instanceData.businessKey} />
                                        <DescriptionItem label="状态" value={getStatusBadge(instanceData.status)} />
                                        <DescriptionItem 
                                            label="开始时间" 
                                            value={dayjs(instanceData.startTime).format('YYYY-MM-DD HH:mm:ss')} 
                                        />
                                        <DescriptionItem 
                                            label="结束时间" 
                                            value={instanceData.endTime ? dayjs(instanceData.endTime).format('YYYY-MM-DD HH:mm:ss') : '暂无'} 
                                        />
                                        {instanceData.startTime && instanceData.endTime && (
                                            <DescriptionItem 
                                                label="总耗时" 
                                                value={`${dayjs(instanceData.endTime).diff(dayjs(instanceData.startTime), 'second')}秒`} 
                                            />
                                        )}
                                        <DescriptionItem label="执行节点数" value={instanceData.stages.length} />
                                    </div>
                                </CardContent>
            </Card>
                        </TabsContent>
                    </Tabs>
                </DialogPrimitive.Content>
            </DialogPortal>
        </Dialog>
    );
};

export default DetailModal;
