import { useState, useEffect } from 'react';
import { AIModelMonitor } from '../ai/AIModelMonitor';
import { AIAuditLog } from '../ai/AIAuditLog';
import { AIAlertManagement } from '../ai/AIAlertManagement';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Progress } from '../ui/progress';
import { Switch } from '../ui/switch';
import {
  Monitor,
  Search,
  Download,
  RefreshCw,
  Filter,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Activity,
  Eye,
  Settings,
  Plus,
  Bell,
  BellRing,
  BellOff,
  Clock,
  Calendar,
  TrendingUp,
  TrendingDown,
  Zap,
  Server,
  Database,
  Cpu,
  MemoryStick,
  HardDrive,
  Wifi,
  AlertCircle,
  Info,
  FileText,
  History,
  Code,
  GitBranch,
  Layers,
  Target,
  BarChart3,
  Mail,
  MessageSquare,
  Smartphone,
  Play,
  Pause,
  StopCircle,
  ChevronRight,
  ExternalLink,
  Copy,
  Edit,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  AreaChart,
  Area,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface AIMonitoringCenterProps {
  activePath?: string;
}

type ModelHealth = '健康' | '警告' | '故障';
type AlertLevel = '严重' | '警告' | '提示';
type AlertStatus = '未处理' | '处理中' | '已处理' | '已忽略';
type NotifyChannel = '短信' | '邮件' | '站内信';

interface ModelMetrics {
  id: string;
  modelName: string;
  modelVersion: string;
  health: ModelHealth;
  callCount: number;
  successRate: number;
  avgResponseTime: number;
  p95ResponseTime: number;
  p99ResponseTime: number;
  cpuUsage: number;
  memoryUsage: number;
  diskUsage: number;
  errorRate: number;
  lastCallTime: string;
  uptime: number;
}

interface AuditLog {
  id: string;
  traceId: string;
  decisionNo: string;
  fieldName: string;
  decisionType: string;
  createTime: string;
  steps: {
    step: string;
    timestamp: string;
    duration: number;
    status: 'success' | 'failed';
    details: any;
  }[];
  totalDuration: number;
  finalStatus: 'success' | 'failed';
}

interface AlertRule {
  id: string;
  ruleName: string;
  ruleType: string;
  condition: string;
  threshold: string;
  level: AlertLevel;
  status: '启用' | '禁用';
  notifyChannels: NotifyChannel[];
  notifyUsers: string[];
  createTime: string;
  triggeredCount: number;
}

interface Alert {
  id: string;
  alertNo: string;
  ruleName: string;
  level: AlertLevel;
  title: string;
  content: string;
  source: string;
  triggerTime: string;
  notifyChannels: NotifyChannel[];
  status: AlertStatus;
  handler?: string;
  handleTime?: string;
  handleNote?: string;
}

export function AIMonitoringCenter({ activePath }: AIMonitoringCenterProps) {
  // 如果是模型监控路径，直接返回模型监控组件
  if (activePath && activePath.includes('/monitoring/model')) {
    return <AIModelMonitor activePath={activePath} />;
  }

  // 如果是审计日志路径，直接返回审计日志组件
  if (activePath && activePath.includes('/monitoring/audit')) {
    return <AIAuditLog activePath={activePath} />;
  }

  // 如果是告警管理路径，直接返回告警管理组件
  if (activePath && activePath.includes('/monitoring/alert')) {
    return <AIAlertManagement activePath={activePath} />;
  }

  return <AIMonitoringCenterContent activePath={activePath} />;
}

function AIMonitoringCenterContent({ activePath }: AIMonitoringCenterProps) {
  const [activeTab, setActiveTab] = useState('audit');
  const [showAlertRuleDialog, setShowAlertRuleDialog] = useState(false);
  const [showAlertDetailDialog, setShowAlertDetailDialog] = useState(false);
  const [showLogDetailDialog, setShowLogDetailDialog] = useState(false);
  const [selectedAlert, setSelectedAlert] = useState<Alert | null>(null);
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/monitoring/audit')) {
        setActiveTab('audit');
      } else if (activePath.includes('/monitoring/alert')) {
        setActiveTab('alert');
      }
    }
  }, [activePath]);

  // 模型监控数据
  const [modelMetrics] = useState<ModelMetrics[]>([
    {
      id: 'model-1',
      modelName: '病虫害识别模型',
      modelVersion: 'v1.8.0',
      health: '健康',
      callCount: 5620,
      successRate: 98.7,
      avgResponseTime: 180,
      p95ResponseTime: 350,
      p99ResponseTime: 520,
      cpuUsage: 45,
      memoryUsage: 62,
      diskUsage: 38,
      errorRate: 1.3,
      lastCallTime: '2024-10-15 18:30:25',
      uptime: 99.8,
    },
    {
      id: 'model-2',
      modelName: '灌溉优化模型',
      modelVersion: 'v2.1.0',
      health: '健康',
      callCount: 1850,
      successRate: 99.5,
      avgResponseTime: 230,
      p95ResponseTime: 420,
      p99ResponseTime: 680,
      cpuUsage: 38,
      memoryUsage: 54,
      diskUsage: 42,
      errorRate: 0.5,
      lastCallTime: '2024-10-15 18:05:32',
      uptime: 99.9,
    },
    {
      id: 'model-3',
      modelName: '施肥决策模型',
      modelVersion: 'v3.0.1',
      health: '警告',
      callCount: 425,
      successRate: 94.2,
      avgResponseTime: 350,
      p95ResponseTime: 850,
      p99ResponseTime: 1200,
      cpuUsage: 78,
      memoryUsage: 85,
      diskUsage: 68,
      errorRate: 5.8,
      lastCallTime: '2024-10-15 16:15:00',
      uptime: 96.5,
    },
  ]);

  // 审计日志数据
  const [auditLogs] = useState<AuditLog[]>([
    {
      id: 'log-1',
      traceId: 'TRACE-20241015-001',
      decisionNo: 'DEC-20241015-001',
      fieldName: '1号大棚',
      decisionType: '病虫害预警',
      createTime: '2024-10-15 14:32:18',
      steps: [
        {
          step: '数据输入',
          timestamp: '2024-10-15 14:32:18.123',
          duration: 50,
          status: 'success',
          details: {
            source: '监控摄像头-CAM001',
            dataSize: '2.3MB',
            fields: ['图像分析', '温度', '湿度'],
          },
        },
        {
          step: '模型计算',
          timestamp: '2024-10-15 14:32:18.173',
          duration: 1800,
          status: 'success',
          details: {
            modelName: '病虫害识别模型',
            modelVersion: 'v1.8.0',
            confidence: 0.94,
            result: '番茄早疫病',
          },
        },
        {
          step: '规则匹配',
          timestamp: '2024-10-15 14:32:19.973',
          duration: 120,
          status: 'success',
          details: {
            rulesMatched: 2,
            rulesApplied: ['病虫害预警等级判定', '高温高湿病害风险'],
            score: 0.86,
          },
        },
        {
          step: '决策生成',
          timestamp: '2024-10-15 14:32:20.093',
          duration: 80,
          status: 'success',
          details: {
            decisionLevel: '紧急',
            confidence: 0.94,
          },
        },
        {
          step: '执行动作',
          timestamp: '2024-10-15 14:32:20.173',
          duration: 150,
          status: 'success',
          details: {
            action: '发送预警通知',
            recipients: 2,
            channels: ['短信', '站内信'],
          },
        },
      ],
      totalDuration: 2200,
      finalStatus: 'success',
    },
    {
      id: 'log-2',
      traceId: 'TRACE-20241015-002',
      decisionNo: 'DEC-20241015-002',
      fieldName: '3号田块',
      decisionType: '灌溉决策',
      createTime: '2024-10-15 18:05:32',
      steps: [
        {
          step: '数据输入',
          timestamp: '2024-10-15 18:05:32.100',
          duration: 45,
          status: 'success',
          details: {
            source: '土壤传感器-SOIL003',
            dataSize: '1.2KB',
            fields: ['土壤湿度', '温度', '降水预报'],
          },
        },
        {
          step: '模型���算',
          timestamp: '2024-10-15 18:05:32.145',
          duration: 2300,
          status: 'success',
          details: {
            modelName: '灌溉优化模型',
            modelVersion: 'v2.1.0',
            confidence: 0.92,
            result: { 建议灌溉量: 550, 最佳时段: '06:00-08:00' },
          },
        },
        {
          step: '规则匹配',
          timestamp: '2024-10-15 18:05:34.445',
          duration: 100,
          status: 'success',
          details: {
            rulesMatched: 1,
            rulesApplied: ['土壤湿度阈值灌溉规则'],
          },
        },
        {
          step: '决策生成',
          timestamp: '2024-10-15 18:05:34.545',
          duration: 70,
          status: 'success',
          details: {
            decisionLevel: '重要',
            confidence: 0.92,
          },
        },
        {
          step: '执行动作',
          timestamp: '2024-10-15 18:05:34.615',
          duration: 180,
          status: 'success',
          details: {
            action: '生成控制指令',
            deviceId: 'DEV-IRT-001',
            commandSent: true,
          },
        },
      ],
      totalDuration: 2695,
      finalStatus: 'success',
    },
  ]);

  // 告警规则数据
  const [alertRules] = useState<AlertRule[]>([
    {
      id: 'rule-1',
      ruleName: '模型服务异常告警',
      ruleType: '模型监控',
      condition: '模型服务连续3次调用失败 OR 错误率 > 10%',
      threshold: '错误率 > 10%',
      level: '严重',
      status: '启用',
      notifyChannels: ['短信', '邮件', '站内信'],
      notifyUsers: ['运维负责人', '技术主管'],
      createTime: '2024-09-01',
      triggeredCount: 2,
    },
    {
      id: 'rule-2',
      ruleName: '模型响应时间过长',
      ruleType: '性能监控',
      condition: 'P95响应时间 > 1000ms',
      threshold: 'P95 > 1000ms',
      level: '警告',
      status: '启用',
      notifyChannels: ['邮件', '站内信'],
      notifyUsers: ['运维负责人'],
      createTime: '2024-09-01',
      triggeredCount: 15,
    },
    {
      id: 'rule-3',
      ruleName: '决策生成失败告警',
      ruleType: '决策监控',
      condition: '决策生成失败',
      threshold: '失败次数 > 0',
      level: '严重',
      status: '启用',
      notifyChannels: ['短信', '站内信'],
      notifyUsers: ['系统管理员'],
      createTime: '2024-09-01',
      triggeredCount: 5,
    },
    {
      id: 'rule-4',
      ruleName: '数据质量异常',
      ruleType: '数据质量',
      condition: '数据缺失率 > 20% OR 数据异常值占比 > 15%',
      threshold: '缺失率 > 20%',
      level: '警告',
      status: '启用',
      notifyChannels: ['邮件'],
      notifyUsers: ['数据管理员'],
      createTime: '2024-09-15',
      triggeredCount: 8,
    },
  ]);

  // 告警记录数据
  const [alerts] = useState<Alert[]>([
    {
      id: 'alert-1',
      alertNo: 'ALERT-20241015-001',
      ruleName: '模型响应时间过长',
      level: '警告',
      title: '施肥决策模型响应时间异常',
      content: '施肥决策模型(v3.0.1) P95响应时间达到850ms，超过阈值1000ms的85%，建议关注',
      source: '施肥决策模型 v3.0.1',
      triggerTime: '2024-10-15 16:15:30',
      notifyChannels: ['邮件', '站内信'],
      status: '已处理',
      handler: '张工',
      handleTime: '2024-10-15 16:30:00',
      handleNote: '已优化模型参数，响应时间降至正常范围',
    },
    {
      id: 'alert-2',
      alertNo: 'ALERT-20241015-002',
      ruleName: '数据质量异常',
      level: '警告',
      title: '2号田块传感器数据缺失',
      content: '2号田块土壤传感器在过去1小时内数据缺失率达到25%，请检查传感器状态',
      source: '土壤传感器-SOIL002',
      triggerTime: '2024-10-15 15:20:00',
      notifyChannels: ['邮件'],
      status: '处理中',
      handler: '李工',
      handleTime: '2024-10-15 15:25:00',
    },
    {
      id: 'alert-3',
      alertNo: 'ALERT-20241015-003',
      ruleName: '模型服务异常告警',
      level: '严重',
      title: '产量预测模型服务不可用',
      content: '产量预测模型服务连续5次调用失败，错误率100%，服务可能已宕机',
      source: '产量预测模型 v3.1.2',
      triggerTime: '2024-10-15 12:10:00',
      notifyChannels: ['短信', '邮件', '站内信'],
      status: '未处理',
    },
  ]);

  // 模型调用趋势
  const modelCallTrend = [
    { time: '14:00', 病虫害: 45, 灌溉: 28, 施肥: 12 },
    { time: '15:00', 病虫害: 52, 灌溉: 32, 施肥: 15 },
    { time: '16:00', 病虫害: 48, 灌溉: 30, 施肥: 18 },
    { time: '17:00', 病虫害: 55, 灌溉: 35, 施肥: 14 },
    { time: '18:00', 病虫害: 60, 灌溉: 38, 施肥: 16 },
  ];

  // 模型性能指标
  const modelPerformanceData = modelMetrics.map(m => ({
    name: m.modelName.substring(0, 6),
    响应时间: m.avgResponseTime,
    成功率: m.successRate,
    CPU: m.cpuUsage,
  }));

  // 告警统计
  const alertStats = [
    { level: '严重', count: 1, color: '#ef4444' },
    { level: '警告', count: 2, color: '#f59e0b' },
    { level: '提示', count: 0, color: '#3b82f6' },
  ];

  const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6'];

  const getHealthColor = (health: ModelHealth) => {
    switch (health) {
      case '健康': return 'bg-success-muted text-success-muted-foreground';
      case '警告': return 'bg-warning-muted text-warning-muted-foreground';
      case '故障': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getAlertLevelColor = (level: AlertLevel) => {
    switch (level) {
      case '严重': return 'bg-error-muted text-error-muted-foreground';
      case '警告': return 'bg-warning-muted text-warning-muted-foreground';
      case '提示': return 'bg-info-muted text-info-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getAlertStatusColor = (status: AlertStatus) => {
    switch (status) {
      case '未处理': return 'bg-error-muted text-error-muted-foreground';
      case '处理中': return 'bg-warning-muted text-warning-muted-foreground';
      case '已处理': return 'bg-success-muted text-success-muted-foreground';
      case '已忽略': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const handleHandleAlert = (alertNo: string) => {
    toast.success(`告警 ${alertNo} 已标记为处理中`);
  };

  const handleResolveAlert = (alertNo: string) => {
    toast.success(`告警 ${alertNo} 已处理完成`);
  };

  const handleIgnoreAlert = (alertNo: string) => {
    toast.success(`告警 ${alertNo} 已忽略`);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>监控中心</h2>
          <p className="text-sm text-muted-foreground mt-1">
            全方位监控，保障系统稳定运行
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新数据
          </Button>
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            导出报告
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">模型服务</p>
              <p className="mt-2 text-3xl text-info">{modelMetrics.length}</p>
              <p className="text-xs text-info mt-1">运行中</p>
            </div>
            <Server className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">平均成功率</p>
              <p className="mt-2 text-3xl text-success">
                {(modelMetrics.reduce((sum, m) => sum + m.successRate, 0) / modelMetrics.length).toFixed(1)}%
              </p>
              <p className="text-xs text-success mt-1">系统健康度</p>
            </div>
            <CheckCircle className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">审计日志</p>
              <p className="mt-2 text-3xl text-accent-foreground">{auditLogs.length}</p>
              <p className="text-xs text-accent-foreground mt-1">今日记录</p>
            </div>
            <FileText className="w-12 h-12 text-accent-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">活跃告警</p>
              <p className="mt-2 text-3xl text-red-600">
                {alerts.filter(a => a.status === '未处理' || a.status === '处理中').length}
              </p>
              <p className="text-xs text-red-600 mt-1">待处理告警</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-red-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="model">模型监控</TabsTrigger>
          <TabsTrigger value="audit">全链路审计日志</TabsTrigger>
          <TabsTrigger value="alert">告警管理</TabsTrigger>
        </TabsList>

        {/* 模型监控 */}
        <TabsContent value="model" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Monitor className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">模型监控功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>健康度指标</strong>: 调用次数、成功率、响应时间、资源使用率</li>
                  <li>• <strong>可视化图表</strong>: 实时性能趋势与资源使用情况</li>
                  <li>• <strong>性能分析</strong>: P95/P99响应时间、错误率统计</li>
                  <li>• <strong>资源监控</strong>: CPU、内存、磁盘使用率</li>
                  <li>• <strong>告警功能</strong>: 性能瓶颈与异常服务及时发现</li>
                  <li>• <strong>稳定保障</strong>: 7×24小时持续监控</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 模型列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Server className="w-5 h-5 text-blue-600" />
                模型服务监控
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>模型名称</TableHead>
                  <TableHead>版本</TableHead>
                  <TableHead>健康状态</TableHead>
                  <TableHead>调用统计</TableHead>
                  <TableHead>响应时间</TableHead>
                  <TableHead>资源使用</TableHead>
                  <TableHead>运行时间</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {modelMetrics.map((model) => (
                  <TableRow key={model.id}>
                    <TableCell className="font-medium">{model.modelName}</TableCell>
                    <TableCell className="text-xs">{model.modelVersion}</TableCell>
                    <TableCell>
                      <Badge className={getHealthColor(model.health)}>
                        {model.health}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        <div>调用: {model.callCount}次</div>
                        <div className={model.successRate >= 98 ? 'text-green-600' : 'text-red-600'}>
                          成功率: {model.successRate}%
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        <div>平均: {model.avgResponseTime}ms</div>
                        <div className="text-muted-foreground">P95: {model.p95ResponseTime}ms</div>
                        <div className="text-muted-foreground">P99: {model.p99ResponseTime}ms</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-2">
                        <div>
                          <div className="flex items-center justify-between text-xs mb-1">
                            <span>CPU</span>
                            <span>{model.cpuUsage}%</span>
                          </div>
                          <Progress value={model.cpuUsage} className="h-1" />
                        </div>
                        <div>
                          <div className="flex items-center justify-between text-xs mb-1">
                            <span>内存</span>
                            <span>{model.memoryUsage}%</span>
                          </div>
                          <Progress value={model.memoryUsage} className="h-1" />
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        <div className="text-green-600">在线率: {model.uptime}%</div>
                        <div className="text-muted-foreground">
                          最近: {model.lastCallTime.substring(11)}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Button size="sm" variant="outline">
                        <Eye className="w-3 h-3 mr-1" />
                        详情
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 监控图表 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Activity className="w-4 h-4 text-blue-600" />
                模型调用趋势
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <AreaChart data={modelCallTrend}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="time" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Area type="monotone" dataKey="病虫害" stackId="1" stroke="#f59e0b" fill="#f59e0b" fillOpacity={0.6} />
                  <Area type="monotone" dataKey="灌溉" stackId="1" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.6} />
                  <Area type="monotone" dataKey="施肥" stackId="1" stroke="#10b981" fill="#10b981" fillOpacity={0.6} />
                </AreaChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-green-600" />
                模型性能指标
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <BarChart data={modelPerformanceData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" />
                  <RechartsTooltip />
                  <Legend />
                  <Bar yAxisId="left" dataKey="响应时间" fill="#3b82f6" />
                  <Bar yAxisId="right" dataKey="成功率" fill="#10b981" />
                </BarChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 全链路审计日志 */}
        <TabsContent value="audit" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
            <div className="flex items-start gap-2">
              <FileText className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">全链路审计日志功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>完整流水</strong>: 记录决策任务的完整执行过程</li>
                  <li>• <strong>多维查询</strong>: 按时间、地块、决策ID等条件查询</li>
                  <li>• <strong>全环节覆盖</strong>: 数据输入、模型计算、规则匹配、决策生成、执行动作</li>
                  <li>• <strong>根因分析</strong>: 快速定位问题原因</li>
                  <li>• <strong>性能优化</strong>: 分析各环节耗时，优化性能瓶颈</li>
                  <li>• <strong>合规审计</strong>: 满足合规要求的审计追溯</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 搜索筛选 */}
          <Card className="p-4">
            <div className="flex gap-4">
              <div className="flex-1">
                <Input placeholder="搜索决策编号、追踪ID、地块名称..." prefix={<Search className="w-4 h-4" />} />
              </div>
              <Select defaultValue="all-type">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="决策类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-type">全部类型</SelectItem>
                  <SelectItem value="pest">病虫害预警</SelectItem>
                  <SelectItem value="irrigation">灌溉决策</SelectItem>
                  <SelectItem value="fertilizer">施肥决策</SelectItem>
                </SelectContent>
              </Select>
              <Select defaultValue="today">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="时间范围" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="today">今天</SelectItem>
                  <SelectItem value="week">本周</SelectItem>
                  <SelectItem value="month">本月</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </Card>

          {/* 审计日志列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <History className="w-5 h-5 text-purple-600" />
                审计日志记录
              </h3>
            </div>
            <div className="divide-y">
              {auditLogs.map((log) => (
                <div key={log.id} className="p-4">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h4>{log.decisionType}</h4>
                        <Badge variant="outline">{log.fieldName}</Badge>
                        <Badge className={log.finalStatus === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}>
                          {log.finalStatus === 'success' ? '成功' : '失败'}
                        </Badge>
                      </div>
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {log.createTime}
                        </span>
                        <span className="flex items-center gap-1">
                          <Zap className="w-3 h-3" />
                          总耗时: {log.totalDuration}ms
                        </span>
                        <span className="font-mono">追踪ID: {log.traceId}</span>
                        <span className="font-mono">决策: {log.decisionNo}</span>
                      </div>
                    </div>
                    <Button size="sm" variant="outline" onClick={() => {
                      setSelectedLog(log);
                      setShowLogDetailDialog(true);
                    }}>
                      <Eye className="w-3 h-3 mr-1" />
                      查看详情
                    </Button>
                  </div>

                  {/* 执行步骤时间线 */}
                  <div className="relative pl-8">
                    {log.steps.map((step, idx) => (
                      <div key={idx} className="relative pb-4 last:pb-0">
                        <div className="absolute left-[-1.75rem] top-0 w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center">
                          {step.status === 'success' ? (
                            <CheckCircle className="w-4 h-4 text-blue-600" />
                          ) : (
                            <XCircle className="w-4 h-4 text-red-600" />
                          )}
                        </div>
                        {idx < log.steps.length - 1 && (
                          <div className="absolute left-[-1.25rem] top-6 w-0.5 h-full bg-blue-200"></div>
                        )}
                        <div className="bg-gray-50 p-3 rounded-lg">
                          <div className="flex items-center justify-between mb-2">
                            <h5 className="text-sm">{step.step}</h5>
                            <div className="flex items-center gap-2 text-xs text-muted-foreground">
                              <span>{step.timestamp.substring(11)}</span>
                              <Badge variant="outline">{step.duration}ms</Badge>
                            </div>
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {Object.entries(step.details).slice(0, 2).map(([key, value]) => (
                              <span key={key} className="mr-3">
                                {key}: {typeof value === 'object' ? JSON.stringify(value) : value}
                              </span>
                            ))}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 告警管理 */}
        <TabsContent value="alert" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-red-50 to-orange-50 border-red-200">
            <div className="flex items-start gap-2">
              <Bell className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-red-900">
                <p className="mb-2">告警管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自定义规则</strong>: 灵活配置告警规则与阈值</li>
                  <li>• <strong>多场景覆盖</strong>: 模型服务异常、决策失败、数据质量异常</li>
                  <li>• <strong>多渠道通知</strong>: 短信、邮件、站内信及时触达</li>
                  <li>• <strong>告警分级</strong>: 严重/警告/提示三级分类</li>
                  <li>• <strong>告警收敛</strong>: 避免告警风暴</li>
                  <li>• <strong>处理跟踪</strong>: 完整的告警处理流程管理</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex gap-4">
            <Button className="bg-red-600 hover:bg-red-700" onClick={() => setShowAlertRuleDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              新建规则
            </Button>
            <Button variant="outline">
              <Settings className="w-4 h-4 mr-2" />
              通知设置
            </Button>
          </div>

          {/* 告警统计 */}
          <div className="grid grid-cols-3 gap-4">
            {alertStats.map((stat) => (
              <Card key={stat.level} className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-xs text-muted-foreground">{stat.level}告警</p>
                    <p className="mt-2 text-3xl" style={{ color: stat.color }}>{stat.count}</p>
                  </div>
                  <AlertTriangle className="w-12 h-12 opacity-50" style={{ color: stat.color }} />
                </div>
              </Card>
            ))}
          </div>

          {/* 告警规则 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Settings className="w-5 h-5 text-blue-600" />
                告警规则配置
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>规则名称</TableHead>
                  <TableHead>规则类型</TableHead>
                  <TableHead>触发条件</TableHead>
                  <TableHead>告警等级</TableHead>
                  <TableHead>通知方式</TableHead>
                  <TableHead>触发次数</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {alertRules.map((rule) => (
                  <TableRow key={rule.id}>
                    <TableCell className="font-medium">{rule.ruleName}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{rule.ruleType}</Badge>
                    </TableCell>
                    <TableCell className="max-w-xs">
                      <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                        {rule.condition}
                      </code>
                    </TableCell>
                    <TableCell>
                      <Badge className={getAlertLevelColor(rule.level)}>
                        {rule.level}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-1">
                        {rule.notifyChannels.map((channel, idx) => (
                          <Badge key={idx} variant="outline" className="text-xs">
                            {channel === '短信' && <Smartphone className="w-3 h-3 mr-1" />}
                            {channel === '邮件' && <Mail className="w-3 h-3 mr-1" />}
                            {channel === '站内信' && <MessageSquare className="w-3 h-3 mr-1" />}
                            {channel}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell className="text-xs">{rule.triggeredCount}次</TableCell>
                    <TableCell>
                      <Switch checked={rule.status === '启用'} />
                    </TableCell>
                    <TableCell>
                      <Button size="sm" variant="outline">
                        <Edit className="w-3 h-3" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 告警记录 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <BellRing className="w-5 h-5 text-red-600" />
                告警记录
              </h3>
            </div>
            <div className="divide-y">
              {alerts.map((alert) => (
                <div key={alert.id} className="p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h4>{alert.title}</h4>
                        <Badge className={getAlertLevelColor(alert.level)}>
                          {alert.level}
                        </Badge>
                        <Badge className={getAlertStatusColor(alert.status)}>
                          {alert.status}
                        </Badge>
                        <span className="text-xs text-muted-foreground">#{alert.alertNo}</span>
                      </div>
                      <p className="text-sm text-muted-foreground mb-2">{alert.content}</p>
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {alert.triggerTime}
                        </span>
                        <span>规则: {alert.ruleName}</span>
                        <span>来源: {alert.source}</span>
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center justify-between">
                    <div className="flex gap-2">
                      {alert.notifyChannels.map((channel, idx) => (
                        <Badge key={idx} variant="outline" className="text-xs">
                          {channel}
                        </Badge>
                      ))}
                    </div>
                    <div className="flex gap-2">
                      {alert.status === '未处理' && (
                        <Button size="sm" onClick={() => handleHandleAlert(alert.alertNo)}>
                          处理
                        </Button>
                      )}
                      {alert.status === '处理中' && (
                        <Button size="sm" className="bg-green-600 hover:bg-green-700" onClick={() => handleResolveAlert(alert.alertNo)}>
                          完成
                        </Button>
                      )}
                      <Button size="sm" variant="outline" onClick={() => {
                        setSelectedAlert(alert);
                        setShowAlertDetailDialog(true);
                      }}>
                        <Eye className="w-3 h-3 mr-1" />
                        详情
                      </Button>
                      {(alert.status === '未处理' || alert.status === '处理中') && (
                        <Button size="sm" variant="outline" onClick={() => handleIgnoreAlert(alert.alertNo)}>
                          忽略
                        </Button>
                      )}
                    </div>
                  </div>

                  {alert.handler && (
                    <div className="mt-3 p-3 bg-green-50 rounded-lg text-sm">
                      <div className="flex items-center gap-2 mb-1">
                        <CheckCircle className="w-4 h-4 text-green-600" />
                        <span className="font-medium">处理信息</span>
                      </div>
                      <div className="text-xs space-y-1">
                        <p>处理人: {alert.handler}</p>
                        <p>处理时间: {alert.handleTime}</p>
                        {alert.handleNote && <p>处理说明: {alert.handleNote}</p>}
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 告警规则对话框 */}
      <Dialog open={showAlertRuleDialog} onOpenChange={setShowAlertRuleDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>新建告警规则</DialogTitle>
            <DialogDescription>
              配置告警触发条件和通知方式
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>规则名称</Label>
              <Input placeholder="输入规则名称" />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>规则类型</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择规则类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="model">模型监控</SelectItem>
                    <SelectItem value="performance">性能监控</SelectItem>
                    <SelectItem value="decision">决策监控</SelectItem>
                    <SelectItem value="data">数据质量</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>告警等级</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择告警等级" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="critical">严重</SelectItem>
                    <SelectItem value="warning">警告</SelectItem>
                    <SelectItem value="info">提示</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>触发条件</Label>
              <Textarea 
                placeholder="例如: 错误率 > 10% OR 连续失败次数 > 3" 
                rows={3}
              />
            </div>

            <div>
              <Label>通知方式</Label>
              <div className="flex gap-4 mt-2">
                <label className="flex items-center gap-2">
                  <input type="checkbox" />
                  <span className="text-sm">短信</span>
                </label>
                <label className="flex items-center gap-2">
                  <input type="checkbox" />
                  <span className="text-sm">邮件</span>
                </label>
                <label className="flex items-center gap-2">
                  <input type="checkbox" />
                  <span className="text-sm">站内信</span>
                </label>
              </div>
            </div>

            <div>
              <Label>通知对象</Label>
              <Input placeholder="输入通知人员，多个用逗号分隔" />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAlertRuleDialog(false)}>
              取消
            </Button>
            <Button className="bg-red-600 hover:bg-red-700">
              创建规则
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 告警详情对话框 */}
      <Dialog open={showAlertDetailDialog} onOpenChange={setShowAlertDetailDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>告警详情</DialogTitle>
            <DialogDescription>
              告警编号: {selectedAlert?.alertNo}
            </DialogDescription>
          </DialogHeader>

          {selectedAlert && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>告警标题</Label>
                  <div className="field-value">{selectedAlert.title}</div>
                </div>
                <div>
                  <Label>告警等级</Label>
                  <div className="field-value">
                    <Badge className={getAlertLevelColor(selectedAlert.level)}>
                      {selectedAlert.level}
                    </Badge>
                  </div>
                </div>
              </div>

              <div>
                <Label>告警内容</Label>
                <div className="field-value">{selectedAlert.content}</div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>告警来源</Label>
                  <div className="field-value">{selectedAlert.source}</div>
                </div>
                <div>
                  <Label>触发时间</Label>
                  <div className="field-value">{selectedAlert.triggerTime}</div>
                </div>
              </div>

              <div>
                <Label>通知方式</Label>
                <div className="field-value">
                  <div className="flex gap-2">
                    {selectedAlert.notifyChannels.map((channel, idx) => (
                      <Badge key={idx} variant="outline">{channel}</Badge>
                    ))}
                  </div>
                </div>
              </div>

              <div>
                <Label>处理状态</Label>
                <div className="field-value">
                  <Badge className={getAlertStatusColor(selectedAlert.status)}>
                    {selectedAlert.status}
                  </Badge>
                </div>
              </div>

              {selectedAlert.handler && (
                <>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>处理人</Label>
                      <div className="field-value">{selectedAlert.handler}</div>
                    </div>
                    <div>
                      <Label>处理时间</Label>
                      <div className="field-value">{selectedAlert.handleTime}</div>
                    </div>
                  </div>
                  {selectedAlert.handleNote && (
                    <div>
                      <Label>处理说明</Label>
                      <div className="field-value">{selectedAlert.handleNote}</div>
                    </div>
                  )}
                </>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAlertDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 日志详情对话框 */}
      <Dialog open={showLogDetailDialog} onOpenChange={setShowLogDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>全链路审计日志详情</DialogTitle>
            <DialogDescription>
              追踪ID: {selectedLog?.traceId}
            </DialogDescription>
          </DialogHeader>

          {selectedLog && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>决策编号</Label>
                  <div className="field-value font-mono">{selectedLog.decisionNo}</div>
                </div>
                <div>
                  <Label>决策类型</Label>
                  <div className="field-value">{selectedLog.decisionType}</div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>地块名称</Label>
                  <div className="field-value">{selectedLog.fieldName}</div>
                </div>
                <div>
                  <Label>创建时间</Label>
                  <div className="field-value">{selectedLog.createTime}</div>
                </div>
              </div>

              <div>
                <Label>执行步骤详情</Label>
                <div className="field-value">
                  <div className="space-y-3">
                    {selectedLog.steps.map((step, idx) => (
                      <Card key={idx} className="p-4">
                        <div className="flex items-center justify-between mb-2">
                          <h5 className="flex items-center gap-2">
                            <span className="w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-xs">
                              {idx + 1}
                            </span>
                            {step.step}
                          </h5>
                          <Badge variant="outline">{step.duration}ms</Badge>
                        </div>
                        <div className="text-xs text-muted-foreground mb-2">
                          时间戳: {step.timestamp}
                        </div>
                        <div className="bg-gray-50 p-3 rounded">
                          <pre className="text-xs overflow-auto">
                            {JSON.stringify(step.details, null, 2)}
                          </pre>
                        </div>
                      </Card>
                    ))}
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>总执行时间</Label>
                  <div className="field-value">{selectedLog.totalDuration}ms</div>
                </div>
                <div>
                  <Label>最终状态</Label>
                  <div className="field-value">
                    <Badge className={selectedLog.finalStatus === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}>
                      {selectedLog.finalStatus === 'success' ? '成功' : '失败'}
                    </Badge>
                  </div>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowLogDetailDialog(false)}>
              关闭
            </Button>
            <Button>
              <Copy className="w-4 h-4 mr-2" />
              复制日志
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
