import { useState, useEffect } from 'react';
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 { Label } from '../ui/label';
import { Switch } from '../ui/switch';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Progress } from '../ui/progress';
import {
  Activity,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Clock,
  Cpu,
  HardDrive,
  Zap,
  TrendingUp,
  TrendingDown,
  Wifi,
  WifiOff,
  Bell,
  BellOff,
  Eye,
  Settings,
  RefreshCw,
  Download,
  Filter,
  Search,
  BarChart3,
  PieChart,
  Server,
  Database,
  AlertCircle,
  Info,
  Calendar,
  Target,
  Gauge,
  CircleDot,
  Radio,
  Signal,
  SignalHigh,
  SignalLow,
  SignalMedium,
  Flame,
  Snowflake,
  Wind,
  Thermometer,
  Power,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  PieChart as RechartsPie,
  Pie,
  Cell,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';

interface AIModelMonitorProps {
  activePath?: string;
}

// 模型状态
type ModelStatus = 'online' | 'offline' | 'warning' | 'error';

// 告警级别
type AlertLevel = 'info' | 'warning' | 'critical';

// 模型服务
interface ModelService {
  id: string;
  modelNo: string;
  modelName: string;
  modelType: string;
  version: string;
  endpoint: string;
  
  // 状态信息
  status: ModelStatus;
  uptime: number; // 运行时长(小时)
  lastHealthCheck: string;
  
  // 性能指标
  metrics: {
    totalCalls: number;
    successCalls: number;
    failedCalls: number;
    successRate: number;
    avgResponseTime: number; // 毫秒
    maxResponseTime: number;
    minResponseTime: number;
    
    // 资源使用率
    cpuUsage: number; // 百分比
    memoryUsage: number; // 百分比
    diskUsage: number; // 百分比
    networkUsage: number; // Mbps
  };
  
  // QPS
  qps: {
    current: number;
    peak: number;
    average: number;
  };
  
  // 告警信息
  alerts: number;
  hasActiveAlert: boolean;
}

// 告警记录
interface Alert {
  id: string;
  alertNo: string;
  modelId: string;
  modelName: string;
  level: AlertLevel;
  type: string;
  message: string;
  value: number;
  threshold: number;
  triggeredAt: string;
  acknowledged: boolean;
  acknowledgedBy?: string;
  acknowledgedAt?: string;
  resolved: boolean;
  resolvedAt?: string;
}

// 告警规则
interface AlertRule {
  id: string;
  ruleName: string;
  metric: string;
  condition: 'gt' | 'lt' | 'eq';
  threshold: number;
  level: AlertLevel;
  enabled: boolean;
  notifyChannels: string[];
}

export function AIModelMonitor({ activePath }: AIModelMonitorProps) {
  const [selectedModel, setSelectedModel] = useState<ModelService | null>(null);
  const [showModelDetail, setShowModelDetail] = useState(false);
  const [showAlertConfig, setShowAlertConfig] = useState(false);
  const [showAlertDetail, setShowAlertDetail] = useState(false);
  const [showModelAlerts, setShowModelAlerts] = useState(false);
  const [selectedAlert, setSelectedAlert] = useState<Alert | null>(null);
  const [selectedModelForAlerts, setSelectedModelForAlerts] = useState<ModelService | null>(null);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [refreshInterval, setRefreshInterval] = useState(5); // 秒
  
  // 筛选条件
  const [filters, setFilters] = useState({
    status: 'all',
    type: 'all',
    searchText: '',
  });

  // 模型服务列表
  const [models] = useState<ModelService[]>([
    {
      id: 'model_001',
      modelNo: 'MODEL-001',
      modelName: '作物需水预测模型',
      modelType: '需水预测',
      version: 'v2.1.0',
      endpoint: 'http://ai-service:8001/predict/water-demand',
      status: 'online',
      uptime: 168.5,
      lastHealthCheck: '2024-10-23 17:30:00',
      metrics: {
        totalCalls: 15847,
        successCalls: 15621,
        failedCalls: 226,
        successRate: 98.6,
        avgResponseTime: 125,
        maxResponseTime: 890,
        minResponseTime: 45,
        cpuUsage: 42,
        memoryUsage: 68,
        diskUsage: 35,
        networkUsage: 15.2,
      },
      qps: {
        current: 35,
        peak: 127,
        average: 42,
      },
      alerts: 0,
      hasActiveAlert: false,
    },
    {
      id: 'model_002',
      modelNo: 'MODEL-002',
      modelName: '病虫害识别模型',
      modelType: '图像识别',
      version: 'v1.8.0',
      endpoint: 'http://ai-service:8002/predict/disease',
      status: 'online',
      uptime: 240.2,
      lastHealthCheck: '2024-10-23 17:30:05',
      metrics: {
        totalCalls: 8932,
        successCalls: 8654,
        failedCalls: 278,
        successRate: 96.9,
        avgResponseTime: 385,
        maxResponseTime: 1520,
        minResponseTime: 120,
        cpuUsage: 75,
        memoryUsage: 82,
        diskUsage: 58,
        networkUsage: 28.6,
      },
      qps: {
        current: 18,
        peak: 85,
        average: 28,
      },
      alerts: 2,
      hasActiveAlert: true,
    },
    {
      id: 'model_003',
      modelNo: 'MODEL-003',
      modelName: '产量预测模型',
      modelType: '产量预测',
      version: 'v3.0.1',
      endpoint: 'http://ai-service:8003/predict/yield',
      status: 'warning',
      uptime: 96.8,
      lastHealthCheck: '2024-10-23 17:29:58',
      metrics: {
        totalCalls: 3245,
        successCalls: 3056,
        failedCalls: 189,
        successRate: 94.2,
        avgResponseTime: 580,
        maxResponseTime: 2150,
        minResponseTime: 180,
        cpuUsage: 88,
        memoryUsage: 91,
        diskUsage: 72,
        networkUsage: 42.3,
      },
      qps: {
        current: 12,
        peak: 65,
        average: 18,
      },
      alerts: 3,
      hasActiveAlert: true,
    },
    {
      id: 'model_004',
      modelNo: 'MODEL-004',
      modelName: '施肥决策模型',
      modelType: '决策优化',
      version: 'v2.3.0',
      endpoint: 'http://ai-service:8004/predict/fertilizer',
      status: 'online',
      uptime: 312.6,
      lastHealthCheck: '2024-10-23 17:30:02',
      metrics: {
        totalCalls: 6789,
        successCalls: 6712,
        failedCalls: 77,
        successRate: 98.9,
        avgResponseTime: 95,
        maxResponseTime: 425,
        minResponseTime: 35,
        cpuUsage: 35,
        memoryUsage: 52,
        diskUsage: 28,
        networkUsage: 8.5,
      },
      qps: {
        current: 22,
        peak: 98,
        average: 32,
      },
      alerts: 0,
      hasActiveAlert: false,
    },
    {
      id: 'model_005',
      modelNo: 'MODEL-005',
      modelName: '生长阶段识别模型',
      modelType: '图像识别',
      version: 'v1.5.2',
      endpoint: 'http://ai-service:8005/predict/growth-stage',
      status: 'error',
      uptime: 0,
      lastHealthCheck: '2024-10-23 17:15:30',
      metrics: {
        totalCalls: 1245,
        successCalls: 0,
        failedCalls: 1245,
        successRate: 0,
        avgResponseTime: 0,
        maxResponseTime: 0,
        minResponseTime: 0,
        cpuUsage: 0,
        memoryUsage: 0,
        diskUsage: 0,
        networkUsage: 0,
      },
      qps: {
        current: 0,
        peak: 0,
        average: 0,
      },
      alerts: 5,
      hasActiveAlert: true,
    },
  ]);

  // 告警记录
  const [alerts] = useState<Alert[]>([
    {
      id: 'alert_001',
      alertNo: 'ALERT-20241023-001',
      modelId: 'model_002',
      modelName: '病虫害识别模型',
      level: 'warning',
      type: 'CPU使用率过高',
      message: 'CPU使用率持续超过70%阈值，当前值75%',
      value: 75,
      threshold: 70,
      triggeredAt: '2024-10-23 16:45:00',
      acknowledged: false,
      resolved: false,
    },
    {
      id: 'alert_002',
      alertNo: 'ALERT-20241023-002',
      modelId: 'model_002',
      modelName: '病虫害识别模型',
      level: 'warning',
      type: '内存使用率过高',
      message: '内存使用率超过80%阈值，当前值82%',
      value: 82,
      threshold: 80,
      triggeredAt: '2024-10-23 17:10:00',
      acknowledged: false,
      resolved: false,
    },
    {
      id: 'alert_003',
      alertNo: 'ALERT-20241023-003',
      modelId: 'model_003',
      modelName: '产量预测模型',
      level: 'critical',
      type: 'CPU使用率过高',
      message: 'CPU使用率达到临界值，当前值88%',
      value: 88,
      threshold: 85,
      triggeredAt: '2024-10-23 17:20:00',
      acknowledged: false,
      resolved: false,
    },
    {
      id: 'alert_004',
      alertNo: 'ALERT-20241023-004',
      modelId: 'model_003',
      modelName: '产量预测模型',
      level: 'critical',
      type: '内存使用率过高',
      message: '内存使用率达到临界值，当前值91%',
      value: 91,
      threshold: 90,
      triggeredAt: '2024-10-23 17:22:00',
      acknowledged: false,
      resolved: false,
    },
    {
      id: 'alert_005',
      alertNo: 'ALERT-20241023-005',
      modelId: 'model_003',
      modelName: '产量预测模型',
      level: 'warning',
      type: '响应时间过长',
      message: '平均响应时间超过500ms阈值，当前值580ms',
      value: 580,
      threshold: 500,
      triggeredAt: '2024-10-23 17:25:00',
      acknowledged: false,
      resolved: false,
    },
    {
      id: 'alert_006',
      alertNo: 'ALERT-20241023-006',
      modelId: 'model_005',
      modelName: '生长阶段识别模型',
      level: 'critical',
      type: '服务不可用',
      message: '模型服务连接失败，健康检查超时',
      value: 0,
      threshold: 1,
      triggeredAt: '2024-10-23 17:15:30',
      acknowledged: true,
      acknowledgedBy: '运维人员',
      acknowledgedAt: '2024-10-23 17:18:00',
      resolved: false,
    },
  ]);

  // 告警规则
  const [alertRules] = useState<AlertRule[]>([
    {
      id: 'rule_001',
      ruleName: 'CPU使用率告警',
      metric: 'cpuUsage',
      condition: 'gt',
      threshold: 70,
      level: 'warning',
      enabled: true,
      notifyChannels: ['email', 'sms'],
    },
    {
      id: 'rule_002',
      ruleName: 'CPU使用率严重告警',
      metric: 'cpuUsage',
      condition: 'gt',
      threshold: 85,
      level: 'critical',
      enabled: true,
      notifyChannels: ['email', 'sms', 'phone'],
    },
    {
      id: 'rule_003',
      ruleName: '内存使用率告警',
      metric: 'memoryUsage',
      condition: 'gt',
      threshold: 80,
      level: 'warning',
      enabled: true,
      notifyChannels: ['email'],
    },
    {
      id: 'rule_004',
      ruleName: '内存使用率严重告警',
      metric: 'memoryUsage',
      condition: 'gt',
      threshold: 90,
      level: 'critical',
      enabled: true,
      notifyChannels: ['email', 'sms', 'phone'],
    },
    {
      id: 'rule_005',
      ruleName: '响应时间告警',
      metric: 'avgResponseTime',
      condition: 'gt',
      threshold: 500,
      level: 'warning',
      enabled: true,
      notifyChannels: ['email'],
    },
    {
      id: 'rule_006',
      ruleName: '成功率告警',
      metric: 'successRate',
      condition: 'lt',
      threshold: 95,
      level: 'warning',
      enabled: true,
      notifyChannels: ['email', 'sms'],
    },
  ]);

  // 性能趋势数据 (最近24小时)
  const performanceTrend = [
    { time: '00:00', cpu: 35, memory: 52, responseTime: 95, qps: 25 },
    { time: '02:00', cpu: 32, memory: 50, responseTime: 88, qps: 18 },
    { time: '04:00', cpu: 28, memory: 48, responseTime: 82, qps: 12 },
    { time: '06:00', cpu: 42, memory: 58, responseTime: 105, qps: 32 },
    { time: '08:00', cpu: 68, memory: 75, responseTime: 158, qps: 78 },
    { time: '10:00', cpu: 85, memory: 88, responseTime: 245, qps: 115 },
    { time: '12:00', cpu: 78, memory: 82, responseTime: 198, qps: 98 },
    { time: '14:00', cpu: 72, memory: 78, responseTime: 175, qps: 85 },
    { time: '16:00', cpu: 65, memory: 72, responseTime: 152, qps: 72 },
    { time: '17:00', cpu: 58, memory: 68, responseTime: 135, qps: 58 },
  ];

  // 调用统计数据
  const callStats = [
    { date: '10-17', success: 2850, failed: 45 },
    { date: '10-18', success: 3120, failed: 38 },
    { date: '10-19', success: 2980, failed: 52 },
    { date: '10-20', success: 3250, failed: 41 },
    { date: '10-21', success: 3680, failed: 35 },
    { date: '10-22', success: 3420, failed: 48 },
    { date: '10-23', success: 2150, failed: 32 },
  ];

  // 统计数据
  const stats = {
    totalModels: models.length,
    onlineModels: models.filter(m => m.status === 'online').length,
    warningModels: models.filter(m => m.status === 'warning').length,
    errorModels: models.filter(m => m.status === 'error').length,
    activeAlerts: alerts.filter(a => !a.resolved).length,
    criticalAlerts: alerts.filter(a => !a.resolved && a.level === 'critical').length,
    avgSuccessRate: (models.reduce((sum, m) => sum + m.metrics.successRate, 0) / models.length).toFixed(1),
    avgResponseTime: Math.round(models.reduce((sum, m) => sum + m.metrics.avgResponseTime, 0) / models.length),
  };

  const getStatusBadge = (status: ModelStatus) => {
    const config = {
      online: { label: '在线', icon: CheckCircle, className: 'bg-success-muted text-success-muted-foreground border-success' },
      offline: { label: '离线', icon: WifiOff, className: 'bg-muted text-muted-foreground border-border' },
      warning: { label: '警告', icon: AlertTriangle, className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
      error: { label: '错误', icon: XCircle, className: 'bg-error-muted text-error-muted-foreground border-error' },
    };
    const { label, icon: Icon, className } = config[status];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getAlertLevelBadge = (level: AlertLevel) => {
    const config = {
      info: { label: '提示', className: 'bg-info-muted text-info-muted-foreground' },
      warning: { label: '警告', className: 'bg-warning-muted text-warning-muted-foreground' },
      critical: { label: '严重', className: 'bg-error-muted text-error-muted-foreground' },
    };
    const { label, className } = config[level];
    return <Badge className={className}>{label}</Badge>;
  };

  const getHealthScore = (model: ModelService) => {
    // 综合评分：成功率40% + 响应时间30% + 资源使用率30%
    const successScore = model.metrics.successRate;
    const responseScore = Math.max(0, 100 - (model.metrics.avgResponseTime / 10));
    const resourceScore = Math.max(0, 100 - Math.max(model.metrics.cpuUsage, model.metrics.memoryUsage));
    
    return Math.round(successScore * 0.4 + responseScore * 0.3 + resourceScore * 0.3);
  };

  const getHealthColor = (score: number) => {
    if (score >= 90) return 'text-success';
    if (score >= 70) return 'text-info';
    if (score >= 50) return 'text-warning';
    return 'text-error';
  };

  const getResourceIcon = (usage: number) => {
    if (usage >= 90) return <Flame className="w-4 h-4 text-error" />;
    if (usage >= 70) return <Thermometer className="w-4 h-4 text-warning" />;
    if (usage >= 50) return <Wind className="w-4 h-4 text-info" />;
    return <Snowflake className="w-4 h-4 text-success" />;
  };

  const handleViewModel = (model: ModelService) => {
    setSelectedModel(model);
    setShowModelDetail(true);
  };

  const handleViewAlert = (alert: Alert) => {
    setSelectedAlert(alert);
    setShowAlertDetail(true);
  };

  const handleViewModelAlerts = (model: ModelService) => {
    setSelectedModelForAlerts(model);
    setShowModelAlerts(true);
  };

  const handleAcknowledgeAlert = (alertId: string) => {
    toast.success('告警已确认');
  };

  const handleResolveAlert = (alertId: string) => {
    toast.success('告警已处理');
  };

  const handleRefresh = () => {
    toast.info('正在刷新数据...');
  };

  // 自动刷新
  useEffect(() => {
    if (!autoRefresh) return;
    
    const timer = setInterval(() => {
      // 这里可以调用API刷新数据
      console.log('Auto refresh...');
    }, refreshInterval * 1000);
    
    return () => clearInterval(timer);
  }, [autoRefresh, refreshInterval]);

  // 筛选模型
  const filteredModels = models.filter(model => {
    if (filters.status !== 'all' && model.status !== filters.status) return false;
    if (filters.type !== 'all' && model.modelType !== filters.type) return false;
    if (filters.searchText && !model.modelName.toLowerCase().includes(filters.searchText.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-green-50 to-emerald-50 border-green-200">
        <div className="flex items-start gap-3">
          <Activity className="w-6 h-6 text-green-600 flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">模型监控</h2>
            <p className="text-sm text-muted-foreground mb-3">
              实时监控模型服务健康度，包括调用次数、成功率、响应时间、资源使用率等，及时发现性能瓶颈
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Activity className="w-3 h-3 mr-1" />
                实时监控
              </Badge>
              <Badge variant="outline" className="bg-white">
                <BarChart3 className="w-3 h-3 mr-1" />
                性能分析
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Bell className="w-3 h-3 mr-1" />
                智能告警
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Target className="w-3 h-3 mr-1" />
                瓶颈识别
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">模型总数</div>
            <Server className="w-5 h-5 text-blue-500" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.totalModels}</div>
          <div className="text-xs text-muted-foreground">
            在线: {stats.onlineModels} | 异常: {stats.warningModels + stats.errorModels}
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">活跃告警</div>
            <Bell className="w-5 h-5 text-orange-500" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.activeAlerts}</div>
          <div className="text-xs text-red-600">
            严重: {stats.criticalAlerts}条
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">平均成功率</div>
            <Target className="w-5 h-5 text-green-500" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.avgSuccessRate}%</div>
          <div className="text-xs text-muted-foreground">
            总体服务质量
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">平均响应</div>
            <Clock className="w-5 h-5 text-purple-500" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.avgResponseTime}</div>
          <div className="text-xs text-muted-foreground">
            毫秒
          </div>
        </Card>
      </div>

      {/* 控制栏 */}
      <Card className="p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <Label>自动刷新</Label>
              <Switch checked={autoRefresh} onCheckedChange={setAutoRefresh} />
            </div>
            {autoRefresh && (
              <Select value={String(refreshInterval)} onValueChange={(v) => setRefreshInterval(Number(v))}>
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="5">5秒</SelectItem>
                  <SelectItem value="10">10秒</SelectItem>
                  <SelectItem value="30">30秒</SelectItem>
                  <SelectItem value="60">1分钟</SelectItem>
                </SelectContent>
              </Select>
            )}
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={handleRefresh}>
              <RefreshCw className="w-4 h-4 mr-2" />
              刷新
            </Button>
            <Button variant="outline" size="sm" onClick={() => setShowAlertConfig(true)}>
              <Settings className="w-4 h-4 mr-2" />
              告警配置
            </Button>
          </div>
        </div>
      </Card>

      {/* Tab切换 */}
      <Tabs defaultValue="overview" className="space-y-6">
        <TabsList>
          <TabsTrigger value="overview">
            <Gauge className="w-4 h-4 mr-2" />
            总览
          </TabsTrigger>
          <TabsTrigger value="models">
            <Server className="w-4 h-4 mr-2" />
            模型列表
          </TabsTrigger>
          <TabsTrigger value="alerts">
            <Bell className="w-4 h-4 mr-2" />
            告警中心
          </TabsTrigger>
          <TabsTrigger value="performance">
            <TrendingUp className="w-4 h-4 mr-2" />
            性能分析
          </TabsTrigger>
        </TabsList>

        {/* 总览 */}
        <TabsContent value="overview">
          <div className="space-y-6">
            {/* 关键指标 */}
            <div className="grid grid-cols-2 gap-6">
              <Card className="p-6">
                <h3 className="mb-4">性能趋势 (最近24小时)</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <AreaChart data={performanceTrend}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="time" />
                    <YAxis />
                    <RechartsTooltip />
                    <Legend />
                    <Area type="monotone" dataKey="cpu" stroke="#ef4444" fill="#fecaca" name="CPU使用率(%)" />
                    <Area type="monotone" dataKey="memory" stroke="#f59e0b" fill="#fed7aa" name="内存使用率(%)" />
                  </AreaChart>
                </ResponsiveContainer>
              </Card>

              <Card className="p-6">
                <h3 className="mb-4">响应时间与QPS</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart data={performanceTrend}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="time" />
                    <YAxis yAxisId="left" />
                    <YAxis yAxisId="right" orientation="right" />
                    <RechartsTooltip />
                    <Legend />
                    <Line yAxisId="left" type="monotone" dataKey="responseTime" stroke="#8b5cf6" strokeWidth={2} name="响应时间(ms)" />
                    <Line yAxisId="right" type="monotone" dataKey="qps" stroke="#10b981" strokeWidth={2} name="QPS" />
                  </LineChart>
                </ResponsiveContainer>
              </Card>
            </div>

            {/* 模型健康度 */}
            <Card className="p-6">
              <h3 className="mb-4">模型健康度评分</h3>
              <div className="space-y-4">
                {filteredModels.map((model) => {
                  const healthScore = getHealthScore(model);
                  return (
                    <div key={model.id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-3">
                          <div className="w-16 h-16 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                            <span className={`text-2xl font-bold text-white ${getHealthColor(healthScore)}`}>
                              {healthScore}
                            </span>
                          </div>
                          <div>
                            <h4>{model.modelName}</h4>
                            <p className="text-sm text-muted-foreground">{model.modelType} · {model.version}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          {getStatusBadge(model.status)}
                          {model.hasActiveAlert && (
                            <Badge 
                              className="bg-red-600 cursor-pointer hover:bg-red-700 transition-colors"
                              onClick={() => handleViewModelAlerts(model)}
                            >
                              <AlertTriangle className="w-3 h-3 mr-1" />
                              {model.alerts}个告警
                            </Badge>
                          )}
                        </div>
                      </div>
                      
                      <div className="grid grid-cols-4 gap-4">
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">成功率</div>
                          <div className="flex items-center gap-2">
                            <Progress value={model.metrics.successRate} className="h-2" />
                            <span className="text-sm font-medium">{model.metrics.successRate}%</span>
                          </div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">响应时间</div>
                          <div className="flex items-center gap-2">
                            <Clock className="w-4 h-4 text-muted-foreground" />
                            <span className="text-sm font-medium">{model.metrics.avgResponseTime}ms</span>
                          </div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">CPU使用率</div>
                          <div className="flex items-center gap-2">
                            {getResourceIcon(model.metrics.cpuUsage)}
                            <Progress value={model.metrics.cpuUsage} className="h-2 flex-1" />
                            <span className="text-sm font-medium">{model.metrics.cpuUsage}%</span>
                          </div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">内存使用率</div>
                          <div className="flex items-center gap-2">
                            {getResourceIcon(model.metrics.memoryUsage)}
                            <Progress value={model.metrics.memoryUsage} className="h-2 flex-1" />
                            <span className="text-sm font-medium">{model.metrics.memoryUsage}%</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </Card>
          </div>
        </TabsContent>

        {/* 模型列表 */}
        <TabsContent value="models">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>模型服务列表</h3>
            </div>

            {/* 筛选条件 */}
            <div className="grid grid-cols-3 gap-4 mb-4">
              <div>
                <Label>状态筛选</Label>
                <Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="online">在线</SelectItem>
                    <SelectItem value="warning">警告</SelectItem>
                    <SelectItem value="error">错误</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>类型筛选</Label>
                <Select value={filters.type} onValueChange={(value) => setFilters({ ...filters, type: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                    <SelectItem value="需水预测">需水预测</SelectItem>
                    <SelectItem value="图像识别">图像识别</SelectItem>
                    <SelectItem value="产量预测">产量预测</SelectItem>
                    <SelectItem value="决策优化">决策优化</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>搜索</Label>
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索模型..."
                    value={filters.searchText}
                    onChange={(e) => setFilters({ ...filters, searchText: e.target.value })}
                    className="pl-9"
                  />
                </div>
              </div>
            </div>

            {/* 模型列表 */}
            <div className="space-y-4">
              {filteredModels.map((model) => (
                <div key={model.id} className="p-4 border rounded-lg hover:bg-gray-50 transition-colors">
                  <div className="flex items-start gap-4">
                    <div className="w-12 h-12 rounded-lg bg-green-100 flex items-center justify-center flex-shrink-0">
                      <Database className="w-6 h-6 text-green-600" />
                    </div>
                    
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2">
                        <h4 className="truncate">{model.modelName}</h4>
                        {getStatusBadge(model.status)}
                        <Badge variant="outline" className="text-xs">{model.modelType}</Badge>
                        <Badge variant="outline" className="text-xs">{model.version}</Badge>
                        {model.hasActiveAlert && (
                          <Badge className="bg-red-600 text-xs">
                            {model.alerts}个告警
                          </Badge>
                        )}
                      </div>

                      <div className="grid grid-cols-6 gap-4 text-sm mb-3">
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">调用次数</div>
                          <div className="font-medium">{model.metrics.totalCalls.toLocaleString()}</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">成功率</div>
                          <div className="font-medium text-green-600">{model.metrics.successRate}%</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">响应时间</div>
                          <div className="font-medium">{model.metrics.avgResponseTime}ms</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">CPU</div>
                          <div className="font-medium">{model.metrics.cpuUsage}%</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">内存</div>
                          <div className="font-medium">{model.metrics.memoryUsage}%</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">QPS</div>
                          <div className="font-medium">{model.qps.current}</div>
                        </div>
                      </div>

                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span>运行时长: {model.uptime.toFixed(1)}小时</span>
                        <span>最后检查: {model.lastHealthCheck}</span>
                      </div>
                    </div>

                    <Button size="sm" variant="outline" onClick={() => handleViewModel(model)}>
                      <Eye className="w-4 h-4 mr-1" />
                      详情
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 告警中心 */}
        <TabsContent value="alerts">
          <div className="space-y-6">
            {/* 活跃告警 */}
            <Card className="p-6">
              <h3 className="mb-4">活跃告警</h3>
              <div className="space-y-3">
                {alerts.filter(a => !a.resolved).map((alert) => (
                  <div key={alert.id} className="p-4 border rounded-lg bg-red-50 border-red-200">
                    <div className="flex items-start gap-4">
                      <div className="w-10 h-10 rounded-lg bg-red-600 flex items-center justify-center flex-shrink-0">
                        <AlertTriangle className="w-5 h-5 text-white" />
                      </div>
                      
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h4>{alert.type}</h4>
                          {getAlertLevelBadge(alert.level)}
                          {alert.acknowledged && (
                            <Badge className="bg-blue-600">已确认</Badge>
                          )}
                        </div>
                        <p className="text-sm text-muted-foreground mb-2">{alert.message}</p>
                        <div className="flex items-center gap-4 text-xs text-muted-foreground">
                          <span>模型: {alert.modelName}</span>
                          <span>触发时间: {alert.triggeredAt}</span>
                          {alert.acknowledgedAt && (
                            <span>确认时间: {alert.acknowledgedAt}</span>
                          )}
                        </div>
                      </div>

                      <div className="flex gap-2 flex-shrink-0">
                        <Button size="sm" variant="outline" onClick={() => handleViewAlert(alert)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                        {!alert.acknowledged && (
                          <Button size="sm" onClick={() => handleAcknowledgeAlert(alert.id)} className="bg-blue-600 hover:bg-blue-700">
                            确认
                          </Button>
                        )}
                        <Button size="sm" onClick={() => handleResolveAlert(alert.id)} className="bg-green-600 hover:bg-green-700">
                          处理
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </Card>

            {/* 历史告警 */}
            <Card className="p-6">
              <h3 className="mb-4">历史告警</h3>
              <div className="space-y-3">
                {alerts.filter(a => a.resolved).length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground">
                    暂无历史告警记录
                  </div>
                ) : (
                  alerts.filter(a => a.resolved).map((alert) => (
                    <div key={alert.id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between">
                        <div>
                          <h4 className="mb-1">{alert.type}</h4>
                          <p className="text-sm text-muted-foreground">{alert.message}</p>
                        </div>
                        <Badge className="bg-green-600">已处理</Badge>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </Card>
          </div>
        </TabsContent>

        {/* 性能分析 */}
        <TabsContent value="performance">
          <div className="space-y-6">
            <div className="grid grid-cols-2 gap-6">
              {/* 调用统计 */}
              <Card className="p-6">
                <h3 className="mb-4">调用统计 (最近7天)</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={callStats}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis />
                    <RechartsTooltip />
                    <Legend />
                    <Bar dataKey="success" fill="#10b981" name="成功" />
                    <Bar dataKey="failed" fill="#ef4444" name="失败" />
                  </BarChart>
                </ResponsiveContainer>
              </Card>

              {/* 资源使用分布 */}
              <Card className="p-6">
                <h3 className="mb-4">资源使用分布</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <RechartsPie>
                    <Pie
                      data={[
                        { name: 'CPU', value: 42, color: '#ef4444' },
                        { name: '内存', value: 68, color: '#f59e0b' },
                        { name: '磁盘', value: 35, color: '#3b82f6' },
                        { name: '网络', value: 15, color: '#10b981' },
                      ]}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      label={({ name, value }) => `${name}: ${value}%`}
                      outerRadius={100}
                      fill="#8884d8"
                      dataKey="value"
                    >
                      {[
                        { name: 'CPU', value: 42, color: '#ef4444' },
                        { name: '内存', value: 68, color: '#f59e0b' },
                        { name: '磁盘', value: 35, color: '#3b82f6' },
                        { name: '网络', value: 15, color: '#10b981' },
                      ].map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <RechartsTooltip />
                  </RechartsPie>
                </ResponsiveContainer>
              </Card>
            </div>

            {/* 性能瓶颈识别 */}
            <Card className="p-6">
              <h3 className="mb-4">性能瓶颈识别</h3>
              <div className="space-y-4">
                {/* CPU瓶颈 */}
                {models.filter(m => m.metrics.cpuUsage > 70).length > 0 && (
                  <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
                    <div className="flex items-start gap-3">
                      <Cpu className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
                      <div className="flex-1">
                        <h4 className="text-red-800 mb-2">CPU使用率过高</h4>
                        <p className="text-sm text-red-700 mb-2">
                          以下模型CPU使用率超过70%阈值，建议优化或扩容
                        </p>
                        <div className="space-y-1">
                          {models.filter(m => m.metrics.cpuUsage > 70).map(m => (
                            <div key={m.id} className="text-sm text-red-600">
                              • {m.modelName}: {m.metrics.cpuUsage}%
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* 内存瓶颈 */}
                {models.filter(m => m.metrics.memoryUsage > 80).length > 0 && (
                  <div className="p-4 bg-orange-50 border border-orange-200 rounded-lg">
                    <div className="flex items-start gap-3">
                      <HardDrive className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
                      <div className="flex-1">
                        <h4 className="text-orange-800 mb-2">内存使用率过高</h4>
                        <p className="text-sm text-orange-700 mb-2">
                          以下模型内存使用率超过80%阈值，存在内存泄漏风险
                        </p>
                        <div className="space-y-1">
                          {models.filter(m => m.metrics.memoryUsage > 80).map(m => (
                            <div key={m.id} className="text-sm text-orange-600">
                              • {m.modelName}: {m.metrics.memoryUsage}%
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* 响应时间瓶颈 */}
                {models.filter(m => m.metrics.avgResponseTime > 500).length > 0 && (
                  <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <div className="flex items-start gap-3">
                      <Clock className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
                      <div className="flex-1">
                        <h4 className="text-yellow-800 mb-2">响应时间过长</h4>
                        <p className="text-sm text-yellow-700 mb-2">
                          以下模型平均响应时间超过500ms，影响用户体验
                        </p>
                        <div className="space-y-1">
                          {models.filter(m => m.metrics.avgResponseTime > 500).map(m => (
                            <div key={m.id} className="text-sm text-yellow-600">
                              • {m.modelName}: {m.metrics.avgResponseTime}ms
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {models.filter(m => 
                  m.metrics.cpuUsage <= 70 && 
                  m.metrics.memoryUsage <= 80 && 
                  m.metrics.avgResponseTime <= 500
                ).length === models.length && (
                  <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                    <div className="flex items-center gap-3">
                      <CheckCircle className="w-5 h-5 text-green-600" />
                      <p className="text-green-700">所有模型运行正常，暂无性能瓶颈</p>
                    </div>
                  </div>
                )}
              </div>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* 模型详情对话框 */}
      <Dialog open={showModelDetail} onOpenChange={setShowModelDetail}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>模型服务详情</DialogTitle>
            <DialogDescription>
              查看模型的详细监控信息和性能指标
            </DialogDescription>
          </DialogHeader>

          {selectedModel && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="p-3 bg-gray-50 rounded">
                    <div className="text-xs text-muted-foreground mb-1">模型编号</div>
                    <div className="font-medium">{selectedModel.modelNo}</div>
                  </div>
                  <div className="p-3 bg-gray-50 rounded">
                    <div className="text-xs text-muted-foreground mb-1">模型类型</div>
                    <div className="font-medium">{selectedModel.modelType}</div>
                  </div>
                  <div className="p-3 bg-gray-50 rounded">
                    <div className="text-xs text-muted-foreground mb-1">版本</div>
                    <div className="font-medium">{selectedModel.version}</div>
                  </div>
                  <div className="p-3 bg-gray-50 rounded">
                    <div className="text-xs text-muted-foreground mb-1">状态</div>
                    <div>{getStatusBadge(selectedModel.status)}</div>
                  </div>
                </div>
              </div>

              {/* 性能指标 */}
              <div>
                <h4 className="mb-3">性能指标</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-4 bg-blue-50 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">调用次数</div>
                    <div className="text-2xl font-bold text-blue-600">
                      {selectedModel.metrics.totalCalls.toLocaleString()}
                    </div>
                  </div>
                  <div className="p-4 bg-green-50 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">成功率</div>
                    <div className="text-2xl font-bold text-green-600">
                      {selectedModel.metrics.successRate}%
                    </div>
                  </div>
                  <div className="p-4 bg-purple-50 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">平均响应</div>
                    <div className="text-2xl font-bold text-purple-600">
                      {selectedModel.metrics.avgResponseTime}ms
                    </div>
                  </div>
                </div>
              </div>

              {/* 资源使用 */}
              <div>
                <h4 className="mb-3">资源使用率</h4>
                <div className="space-y-3">
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm">CPU使用率</span>
                      <span className="text-sm font-medium">{selectedModel.metrics.cpuUsage}%</span>
                    </div>
                    <Progress value={selectedModel.metrics.cpuUsage} className="h-2" />
                  </div>
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm">内存使用率</span>
                      <span className="text-sm font-medium">{selectedModel.metrics.memoryUsage}%</span>
                    </div>
                    <Progress value={selectedModel.metrics.memoryUsage} className="h-2" />
                  </div>
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm">磁盘使用率</span>
                      <span className="text-sm font-medium">{selectedModel.metrics.diskUsage}%</span>
                    </div>
                    <Progress value={selectedModel.metrics.diskUsage} className="h-2" />
                  </div>
                </div>
              </div>

              {/* QPS信息 */}
              <div>
                <h4 className="mb-3">QPS统计</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-3 bg-gray-50 rounded text-center">
                    <div className="text-xs text-muted-foreground mb-1">当前QPS</div>
                    <div className="text-xl font-bold">{selectedModel.qps.current}</div>
                  </div>
                  <div className="p-3 bg-gray-50 rounded text-center">
                    <div className="text-xs text-muted-foreground mb-1">峰值QPS</div>
                    <div className="text-xl font-bold">{selectedModel.qps.peak}</div>
                  </div>
                  <div className="p-3 bg-gray-50 rounded text-center">
                    <div className="text-xs text-muted-foreground mb-1">平均QPS</div>
                    <div className="text-xl font-bold">{selectedModel.qps.average}</div>
                  </div>
                </div>
              </div>
            </div>
          )}

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

      {/* 告警配置对话框 */}
      <Dialog open={showAlertConfig} onOpenChange={setShowAlertConfig}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>告警规则配置</DialogTitle>
            <DialogDescription>
              配置监控告警的触发条件和通知方式
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {alertRules.map((rule) => (
              <div key={rule.id} className="p-4 border rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-3">
                    <Switch checked={rule.enabled} />
                    <div>
                      <h4>{rule.ruleName}</h4>
                      <p className="text-sm text-muted-foreground">
                        {rule.metric} {rule.condition === 'gt' ? '>' : '<'} {rule.threshold}
                      </p>
                    </div>
                  </div>
                  {getAlertLevelBadge(rule.level)}
                </div>
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <span>通知渠道:</span>
                  {rule.notifyChannels.map((channel, idx) => (
                    <Badge key={idx} variant="outline" className="text-xs">
                      {channel}
                    </Badge>
                  ))}
                </div>
              </div>
            ))}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAlertConfig(false)}>取消</Button>
            <Button onClick={() => {
              setShowAlertConfig(false);
              toast.success('告警规则已保存');
            }}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 模型告警明细对话框 */}
      <Dialog open={showModelAlerts} onOpenChange={setShowModelAlerts}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>告警明细</DialogTitle>
            <DialogDescription>
              {selectedModelForAlerts && `${selectedModelForAlerts.modelName}的所有告警信息`}
            </DialogDescription>
          </DialogHeader>

          {selectedModelForAlerts && (
            <div className="space-y-4">
              {/* 模型基本信息 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-lg bg-blue-600 flex items-center justify-center">
                    <Database className="w-6 h-6 text-white" />
                  </div>
                  <div className="flex-1">
                    <h4>{selectedModelForAlerts.modelName}</h4>
                    <p className="text-sm text-muted-foreground">
                      {selectedModelForAlerts.modelType} · {selectedModelForAlerts.version}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    {getStatusBadge(selectedModelForAlerts.status)}
                    <Badge className="bg-red-600">
                      {alerts.filter(a => a.modelId === selectedModelForAlerts.id && !a.resolved).length}个活跃告警
                    </Badge>
                  </div>
                </div>
              </Card>

              {/* 告警列表 */}
              <div className="space-y-3">
                <h4>告警列表</h4>
                {alerts.filter(a => a.modelId === selectedModelForAlerts.id && !a.resolved).length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground">
                    该模型暂无活跃告警
                  </div>
                ) : (
                  alerts
                    .filter(a => a.modelId === selectedModelForAlerts.id && !a.resolved)
                    .map((alert) => (
                      <div key={alert.id} className="p-4 border rounded-lg bg-red-50 border-red-200">
                        <div className="flex items-start gap-4">
                          <div className="w-10 h-10 rounded-lg bg-red-600 flex items-center justify-center flex-shrink-0">
                            <AlertTriangle className="w-5 h-5 text-white" />
                          </div>
                          
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-2">
                              <h4>{alert.type}</h4>
                              {getAlertLevelBadge(alert.level)}
                              {alert.acknowledged && (
                                <Badge className="bg-blue-600">已确认</Badge>
                              )}
                            </div>
                            <p className="text-sm text-muted-foreground mb-2">{alert.message}</p>
                            <div className="grid grid-cols-2 gap-2 text-xs text-muted-foreground mb-2">
                              <div>告警编号: {alert.alertNo}</div>
                              <div>当前值: {alert.value}</div>
                              <div>触发时间: {alert.triggeredAt}</div>
                              <div>阈值: {alert.threshold}</div>
                              {alert.acknowledgedAt && (
                                <>
                                  <div>确认人: {alert.acknowledgedBy}</div>
                                  <div>确认时间: {alert.acknowledgedAt}</div>
                                </>
                              )}
                            </div>
                          </div>

                          <div className="flex flex-col gap-2 flex-shrink-0">
                            {!alert.acknowledged && (
                              <Button 
                                size="sm" 
                                onClick={() => {
                                  handleAcknowledgeAlert(alert.id);
                                  setShowModelAlerts(false);
                                }} 
                                className="bg-blue-600 hover:bg-blue-700"
                              >
                                确认
                              </Button>
                            )}
                            <Button 
                              size="sm" 
                              onClick={() => {
                                handleResolveAlert(alert.id);
                                setShowModelAlerts(false);
                              }} 
                              className="bg-green-600 hover:bg-green-700"
                            >
                              处理
                            </Button>
                          </div>
                        </div>
                      </div>
                    ))
                )}
              </div>

              {/* 历史告警 */}
              {alerts.filter(a => a.modelId === selectedModelForAlerts.id && a.resolved).length > 0 && (
                <div className="space-y-3">
                  <h4>历史告警</h4>
                  {alerts
                    .filter(a => a.modelId === selectedModelForAlerts.id && a.resolved)
                    .map((alert) => (
                      <div key={alert.id} className="p-4 border rounded-lg bg-gray-50">
                        <div className="flex items-center justify-between">
                          <div>
                            <div className="flex items-center gap-2 mb-1">
                              <h4>{alert.type}</h4>
                              {getAlertLevelBadge(alert.level)}
                              <Badge className="bg-green-600">已处理</Badge>
                            </div>
                            <p className="text-sm text-muted-foreground mb-1">{alert.message}</p>
                            <div className="text-xs text-muted-foreground">
                              触发时间: {alert.triggeredAt} | 处理时间: {alert.resolvedAt}
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                </div>
              )}
            </div>
          )}

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