import { useState } 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 { 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 { ScrollArea } from '../ui/scroll-area';
import { Separator } from '../ui/separator';
import { copyToClipboard } from '../../lib/clipboard';
import {
  FileText,
  Search,
  Download,
  Filter,
  Eye,
  RefreshCw,
  Clock,
  CheckCircle,
  AlertCircle,
  XCircle,
  Database,
  Cpu,
  BookOpen,
  GitBranch,
  Layers,
  Activity,
  BarChart3,
  ArrowRight,
  Zap,
  Info,
  Settings,
  Calendar,
  User,
  FileCode,
  Share2,
  Copy,
  Trash2,
  AlertTriangle,
  TrendingUp,
  Target,
  Gauge,
  Brain,
  Workflow,
  ListChecks,
  Code,
  Box,
  ServerCog,
  FileJson,
  History,
  ChevronRight,
  ChevronDown,
  Play,
  Pause,
  RotateCcw,
  ExternalLink,
  LinkIcon,
  Archive,
  Shield,
  Lock,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface AIDecisionLogProps {
  activePath?: string;
}

// 决策状态
type DecisionStatus = 'success' | 'failed' | 'partial' | 'cancelled';

// 决策级别
type DecisionLevel = 'critical' | 'important' | 'normal' | 'suggestion';

// 日志类型
type LogType = 'decision' | 'model' | 'rule' | 'fusion' | 'system';

// 执行类型
type ExecutionType = 'manual' | 'auto';

// 决策日志
interface DecisionLog {
  id: string;
  timestamp: string;
  status: DecisionStatus;
  level: DecisionLevel;
  type: string;
  scenario: string;
  summary: string;
  executionTime: number;
  executionType: ExecutionType; // 执行类型：manual-手动执行, auto-自动执行
  
  // 触发信息
  trigger: {
    source: string;
    event: string;
    userId: string;
    userName: string;
    conditionsMet?: string; // 自动执行时的触发条件
  };
  
  // 输入数据
  inputData: {
    [key: string]: any;
  };
  
  // 模型服务
  modelService: {
    id: string;
    name: string;
    version: string;
    provider: string;
    callTime: number;
    response: any;
  }[];
  
  // 规则匹配
  rulesMatched: {
    ruleId: string;
    ruleName: string;
    category: string;
    priority: number;
    matched: boolean;
    confidence: number;
    conditions: string[];
    actions: string[];
  }[];
  
  // 融合计算
  fusionProcess: {
    step: string;
    description: string;
    input: any;
    output: any;
    duration: number;
  }[];
  
  // 中间结果
  intermediateResults: {
    stage: string;
    data: any;
    timestamp: string;
  }[];
  
  // 最终决策
  finalDecision: {
    recommendation: string;
    confidence: number;
    reasoning: string;
    actionItems: string[];
    estimatedImpact: string;
  };
  
  // 执行情况
  execution: {
    status: DecisionStatus;
    appliedAt?: string;
    appliedBy?: string;
    result?: string;
    feedback?: string;
  };
}

// 审计追踪
interface AuditTrail {
  id: string;
  decisionId: string;
  action: string;
  timestamp: string;
  user: string;
  details: string;
  ipAddress: string;
}

export function AIDecisionLog({ activePath }: AIDecisionLogProps) {
  const [activeTab, setActiveTab] = useState('logs');
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showAuditDialog, setShowAuditDialog] = useState(false);
  const [selectedLog, setSelectedLog] = useState<DecisionLog | null>(null);
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['input', 'model', 'rules']));
  
  // 筛选条件
  const [filters, setFilters] = useState({
    status: 'all',
    level: 'all',
    type: 'all',
    executionType: 'all' as 'all' | 'manual' | 'auto', // 执行类型筛选
    dateRange: '7days',
    searchText: '',
  });

  // 模拟决策日志数据
  const [decisionLogs] = useState<DecisionLog[]>([
    {
      id: 'log_001',
      timestamp: '2024-10-23 14:30:25',
      status: 'success',
      level: 'important',
      type: '灌溉决策',
      scenario: '开花期缺水灌溉',
      summary: '基于土壤湿度和天气预报生成灌溉建议',
      executionTime: 2.3,
      executionType: 'auto', // 自动执行
      trigger: {
        source: '监测系统',
        event: '土壤湿度低于阈值',
        userId: 'user_001',
        userName: '张三',
        conditionsMet: '土壤湿度28%<30%',
      },
      inputData: {
        cropType: '番茄',
        variety: '金粉808',
        growthStage: '开花期',
        fieldId: 'field_001',
        fieldName: '1号大棚',
        fieldArea: 2.5,
        soilMoisture: 35,
        soilTemperature: 18,
        airTemperature: 28,
        humidity: 65,
        rainfall: 0,
        forecast: '未来3天晴天',
        lastIrrigation: '2024-10-20 18:00',
        lastIrrigationAmount: 100,
      },
      modelService: [
        {
          id: 'model_001',
          name: '作物需水预测模型',
          version: 'v2.1.3',
          provider: 'AgriAI',
          callTime: 0.8,
          response: {
            predictedWaterDemand: 120,
            confidence: 0.92,
            factors: {
              growth: 0.85,
              weather: 0.78,
              soil: 0.88,
            },
          },
        },
        {
          id: 'model_002',
          name: '灌溉时机优化模型',
          version: 'v1.5.0',
          provider: 'AgriAI',
          callTime: 0.5,
          response: {
            optimalTime: '17:00-18:00',
            reason: '避开高温时段，减少蒸发',
            temperature: 26,
          },
        },
      ],
      rulesMatched: [
        {
          ruleId: 'rule_001',
          ruleName: '开花期灌溉规则',
          category: '生长期管理',
          priority: 9,
          matched: true,
          confidence: 0.95,
          conditions: [
            '生长阶段 = 开花期',
            '土壤湿度 < 40%',
            '距上次灌溉 > 2天',
          ],
          actions: [
            '建议立即安排灌溉',
            '灌溉量 = 预测需水量 × 1.1',
            '选择傍晚时段灌溉',
          ],
        },
        {
          ruleId: 'rule_002',
          ruleName: '干旱预警规则',
          category: '风险管理',
          priority: 8,
          matched: true,
          confidence: 0.88,
          conditions: [
            '土壤湿度 < 40%',
            '未来3天无降雨',
            '气温 > 25℃',
          ],
          actions: [
            '提高灌溉优先级',
            '增加监测频率',
            '准备备用水源',
          ],
        },
      ],
      fusionProcess: [
        {
          step: '数据预处理',
          description: '清洗和标准化输入数据',
          input: { raw: '原始传感器数据' },
          output: { normalized: '标准化数据' },
          duration: 0.2,
        },
        {
          step: '模型推理',
          description: '调用需水预测和时机优化模型',
          input: { models: 2 },
          output: { waterDemand: 120, optimalTime: '17:00-18:00' },
          duration: 1.3,
        },
        {
          step: '规则匹配',
          description: '匹配业务规则库',
          input: { totalRules: 15 },
          output: { matchedRules: 2 },
          duration: 0.3,
        },
        {
          step: '结果融合',
          description: '融合模型输出和规则建议',
          input: { modelWeight: 0.6, ruleWeight: 0.5 },
          output: { fusedRecommendation: '立即灌溉120升' },
          duration: 0.5,
        },
      ],
      intermediateResults: [
        {
          stage: '模型推理完成',
          data: {
            waterDemand: 120,
            confidence: 0.92,
            optimalTime: '17:00-18:00',
          },
          timestamp: '2024-10-23 14:30:26',
        },
        {
          stage: '规则匹配完成',
          data: {
            matchedRules: 2,
            highestPriority: 9,
            recommendations: ['立即灌溉', '傍晚时段'],
          },
          timestamp: '2024-10-23 14:30:26',
        },
        {
          stage: '融合计算完成',
          data: {
            finalAmount: 120,
            finalTime: '17:00-18:00',
            confidence: 0.89,
          },
          timestamp: '2024-10-23 14:30:27',
        },
      ],
      finalDecision: {
        recommendation: '建议在今天傍晚17:00-18:00进行灌溉，灌溉量120升，持续时间约45分钟',
        confidence: 0.89,
        reasoning: '综合分析：\n1. 土壤湿度35%，低于开花期最佳湿度(60-70%)\n2. 需水预测模型计算需水量120升(置信度92%)\n3. 未来3天无降雨，蒸发量较大\n4. 开花期是需水关键期，规则优先级高\n5. 傍晚时段灌溉可减少蒸发损失',
        actionItems: [
          '准备灌溉设备，检查管道和喷头',
          '在17:00开始灌溉，避开高温时段',
          '灌溉总量控制在120升，持续约45分钟',
          '灌溉后检查土壤湿度，确保达到60%以上',
          '记录灌溉时间和用水量',
        ],
        estimatedImpact: '预计可使土壤湿度恢复至65%，满足开花期需水要求，避免落花落果',
      },
      execution: {
        status: 'success',
        appliedAt: '2024-10-23 17:05',
        appliedBy: '李四',
        result: '已完成灌溉，实际用水118升，土壤湿度达到63%',
        feedback: '决策准确，效果良好',
      },
    },
    {
      id: 'log_002',
      timestamp: '2024-10-23 10:15:42',
      status: 'success',
      level: 'normal',
      type: '病虫害防治',
      scenario: '早疫病识别与防治',
      summary: '基于图像识别和专家规则生成防治方案',
      executionTime: 3.5,
      trigger: {
        source: 'AI巡检系统',
        event: '病害识别告警',
        userId: 'system',
        userName: '系统自动',
      },
      inputData: {
        cropType: '番茄',
        diseaseType: '早疫病',
        severity: '轻度',
        affectedArea: 5,
        detectionMethod: 'AI图像识别',
        confidence: 0.87,
        imageCount: 12,
        location: '2号大棚东侧',
        weatherCondition: '温暖潮湿',
        lastTreatment: '2024-10-08',
      },
      modelService: [
        {
          id: 'model_003',
          name: '病害识别模型',
          version: 'v3.2.1',
          provider: 'PlantAI',
          callTime: 1.2,
          response: {
            disease: '早疫病',
            confidence: 0.87,
            severity: '轻度',
            affectedLeaves: 15,
          },
        },
        {
          id: 'model_004',
          name: '防治方案推荐模型',
          version: 'v2.0.5',
          provider: 'PlantAI',
          callTime: 0.9,
          response: {
            method: '生物防治',
            product: '枯草芽孢杆菌',
            dosage: '稀释500倍',
            frequency: '每7天一次',
          },
        },
      ],
      rulesMatched: [
        {
          ruleId: 'rule_003',
          ruleName: '早疫病轻度感染处理规则',
          category: '病虫害防治',
          priority: 8,
          matched: true,
          confidence: 0.85,
          conditions: [
            '病害类型 = 早疫病',
            '感染程度 = 轻度',
            '受影响面积 < 10%',
          ],
          actions: [
            '采用生物防治方案',
            '每7天喷施一次',
            '连续处理3次',
            '加强监测',
          ],
        },
      ],
      fusionProcess: [
        {
          step: '图像分析',
          description: 'AI模型识别病害类型和程度',
          input: { images: 12 },
          output: { disease: '早疫病', severity: '轻度', confidence: 0.87 },
          duration: 1.2,
        },
        {
          step: '方案推荐',
          description: '基于病害特征推荐防治方案',
          input: { disease: '早疫病', severity: '轻度' },
          output: { method: '生物防治', product: '枯草芽孢杆菌' },
          duration: 0.9,
        },
        {
          step: '规则验证',
          description: '验证推荐方案符合规则要求',
          input: { recommendation: '生物防治' },
          output: { validated: true, adjustments: [] },
          duration: 0.4,
        },
      ],
      intermediateResults: [
        {
          stage: '病害识别完成',
          data: {
            disease: '早疫病',
            confidence: 0.87,
            severity: '轻度',
          },
          timestamp: '2024-10-23 10:15:43',
        },
      ],
      finalDecision: {
        recommendation: '采用生物防治方案，使用枯草芽孢杆菌制剂，稀释500倍后喷施，每7天一次，连续3次',
        confidence: 0.86,
        reasoning: '早疫病识别准确，感染程度轻度，优先采用生物防治方案，符合绿色农业要求',
        actionItems: [
          '采购枯草芽孢杆菌生物防治剂',
          '配制药液，按说明书比例稀释500倍',
          '在傍晚或阴天进行喷施',
          '重点喷施发病叶片及周围植株',
          '7天后进行第二次喷施',
          '持续观察病情发展',
        ],
        estimatedImpact: '预计7-10天内控制病情扩散，3周内病情好转',
      },
      execution: {
        status: 'success',
        appliedAt: '2024-10-23 15:30',
        appliedBy: '王五',
        result: '已完成第一次喷施，病情得到控制',
        feedback: '方案可行，已安排后续处理',
      },
    },
    {
      id: 'log_003',
      timestamp: '2024-10-22 16:45:10',
      status: 'failed',
      level: 'critical',
      type: '施肥决策',
      scenario: '结果期追肥',
      summary: '模型调用超时，决策生成失败',
      executionTime: 10.2,
      trigger: {
        source: '生长监测系统',
        event: '营养状态检测',
        userId: 'user_002',
        userName: '赵六',
      },
      inputData: {
        cropType: '番茄',
        growthStage: '结果期',
        soilNPK: 'N:90, P:30, K:60',
        leafColor: '偏黄',
        yieldTarget: 9000,
      },
      modelService: [
        {
          id: 'model_005',
          name: '营养诊断模型',
          version: 'v1.8.2',
          provider: 'AgriAI',
          callTime: 10.0,
          response: {
            error: 'Service timeout after 10 seconds',
            code: 'TIMEOUT',
          },
        },
      ],
      rulesMatched: [],
      fusionProcess: [
        {
          step: '模型调用',
          description: '调用营养诊断模型',
          input: { soilNPK: 'N:90, P:30, K:60' },
          output: { error: 'timeout' },
          duration: 10.0,
        },
      ],
      intermediateResults: [],
      finalDecision: {
        recommendation: '模型服务超时，无法生成决策',
        confidence: 0,
        reasoning: '营养诊断模型调用超时，建议检查模型服务状态或手动分析',
        actionItems: [
          '检查模型服务可用性',
          '联系技术支持',
          '考虑使用备用决策方案',
        ],
        estimatedImpact: '决策延迟可能影响施肥时机',
      },
      execution: {
        status: 'failed',
      },
    },
    {
      id: 'log_004',
      timestamp: '2024-10-22 09:20:15',
      status: 'partial',
      level: 'suggestion',
      type: '综合决策',
      scenario: '多因素综合管理',
      summary: '部分模型成功，生成了有限建议',
      executionTime: 4.8,
      trigger: {
        source: '定时任务',
        event: '每日综合分析',
        userId: 'system',
        userName: '系统自动',
      },
      inputData: {
        cropType: '番茄',
        growthStage: '开花期',
        healthScore: 88,
        diseaseRisk: '中',
        weatherForecast: '2天后有雨',
      },
      modelService: [
        {
          id: 'model_006',
          name: '生长预测模型',
          version: 'v2.3.0',
          provider: 'AgriAI',
          callTime: 1.5,
          response: {
            predictedYield: 8500,
            confidence: 0.82,
          },
        },
        {
          id: 'model_007',
          name: '病害风险评估模型',
          version: 'v1.9.1',
          provider: 'PlantAI',
          callTime: 0.0,
          response: {
            error: 'Model not available',
            code: 'SERVICE_DOWN',
          },
        },
      ],
      rulesMatched: [
        {
          ruleId: 'rule_004',
          ruleName: '雨前管理规则',
          category: '天气应对',
          priority: 7,
          matched: true,
          confidence: 0.80,
          conditions: [
            '未来3天有降雨',
            '土壤湿度 > 50%',
          ],
          actions: [
            '暂停灌溉计划',
            '检查排水系统',
            '加固设施',
          ],
        },
      ],
      fusionProcess: [
        {
          step: '数据收集',
          description: '收集各项监测数据',
          input: { sensors: 8 },
          output: { dataComplete: true },
          duration: 0.5,
        },
        {
          step: '模型推理',
          description: '调用多个分析模型',
          input: { models: 2 },
          output: { success: 1, failed: 1 },
          duration: 1.5,
        },
      ],
      intermediateResults: [
        {
          stage: '部分模型完成',
          data: {
            yield: 8500,
            riskAssessment: 'unavailable',
          },
          timestamp: '2024-10-22 09:20:17',
        },
      ],
      finalDecision: {
        recommendation: '基于有限信息，建议关注天气变化，暂停灌溉，检查排水',
        confidence: 0.65,
        reasoning: '病害风险评估模型不可用，仅基于生长预测和天气规则生成建议',
        actionItems: [
          '暂停灌溉计划',
          '检查排水系统',
          '待病害评估模型恢复后重新分析',
        ],
        estimatedImpact: '建议可靠性降低，需人工复核',
      },
      execution: {
        status: 'partial',
        appliedAt: '2024-10-22 10:00',
        appliedBy: '张三',
        result: '已暂停灌溉，排水系统正常',
        feedback: '部分决策可执行',
      },
    },
  ]);

  // 审计追踪数据
  const [auditTrails] = useState<AuditTrail[]>([
    {
      id: 'audit_001',
      decisionId: 'log_001',
      action: '查看决策详情',
      timestamp: '2024-10-23 14:35:00',
      user: '张三',
      details: '查看了灌溉决策的完整日志',
      ipAddress: '192.168.1.100',
    },
    {
      id: 'audit_002',
      decisionId: 'log_001',
      action: '执行决策',
      timestamp: '2024-10-23 17:05:00',
      user: '李四',
      details: '执行灌溉决策，实际灌溉118升',
      ipAddress: '192.168.1.101',
    },
    {
      id: 'audit_003',
      decisionId: 'log_001',
      action: '反馈决策结果',
      timestamp: '2024-10-23 18:30:00',
      user: '李四',
      details: '记录决策执行反馈：效果良好',
      ipAddress: '192.168.1.101',
    },
  ]);

  // 统计数据
  const stats = {
    totalLogs: decisionLogs.length,
    successRate: ((decisionLogs.filter(l => l.status === 'success').length / decisionLogs.length) * 100).toFixed(1),
    avgExecutionTime: (decisionLogs.reduce((sum, l) => sum + l.executionTime, 0) / decisionLogs.length).toFixed(2),
    criticalDecisions: decisionLogs.filter(l => l.level === 'critical').length,
  };

  // 状态分布
  const statusDistribution = [
    { name: '成功', value: decisionLogs.filter(l => l.status === 'success').length, color: '#10b981' },
    { name: '失败', value: decisionLogs.filter(l => l.status === 'failed').length, color: '#ef4444' },
    { name: '部分成功', value: decisionLogs.filter(l => l.status === 'partial').length, color: '#f59e0b' },
    { name: '已取消', value: decisionLogs.filter(l => l.status === 'cancelled').length, color: '#6b7280' },
  ];

  // 类型分布
  const typeDistribution = Array.from(new Set(decisionLogs.map(l => l.type))).map(type => ({
    name: type,
    value: decisionLogs.filter(l => l.type === type).length,
  }));

  // 执行时间趋势
  const executionTimeTrend = decisionLogs.map((log, index) => ({
    name: `决策${index + 1}`,
    time: log.executionTime,
  }));

  const handleViewDetail = (log: DecisionLog) => {
    setSelectedLog(log);
    setShowDetailDialog(true);
  };

  const handleViewAudit = (log: DecisionLog) => {
    setSelectedLog(log);
    setShowAuditDialog(true);
  };

  const handleExportLog = (log: DecisionLog) => {
    toast.success('日志已导出');
  };

  const handleCopyLog = async (log: DecisionLog) => {
    const success = await copyToClipboard(JSON.stringify(log, null, 2));
    if (success) {
      toast.success('日志已复制到剪贴板');
    } else {
      toast.error('复制失败，请重试');
    }
  };

  const toggleSection = (section: string) => {
    const newExpanded = new Set(expandedSections);
    if (newExpanded.has(section)) {
      newExpanded.delete(section);
    } else {
      newExpanded.add(section);
    }
    setExpandedSections(newExpanded);
  };

  const getStatusBadge = (status: DecisionStatus) => {
    const config = {
      success: { label: '成功', icon: CheckCircle, className: 'bg-success-muted text-success-muted-foreground border-success' },
      failed: { label: '失败', icon: XCircle, className: 'bg-error-muted text-error-muted-foreground border-error' },
      partial: { label: '部分成功', icon: AlertCircle, className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
      cancelled: { label: '已取消', icon: XCircle, className: 'bg-muted text-muted-foreground border-border' },
    };
    const { label, icon: Icon, className } = config[status];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getLevelBadge = (level: DecisionLevel) => {
    const config = {
      critical: { label: '紧急', className: 'bg-error-muted text-error-muted-foreground border-error' },
      important: { label: '重要', className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
      normal: { label: '普通', className: 'bg-info-muted text-info-muted-foreground border-info' },
      suggestion: { label: '建议', className: 'bg-muted text-muted-foreground border-border' },
    };
    const { label, className } = config[level];
    return <Badge variant="outline" className={className}>{label}</Badge>;
  };

  // 筛选日志
  const filteredLogs = decisionLogs.filter(log => {
    if (filters.status !== 'all' && log.status !== filters.status) return false;
    if (filters.level !== 'all' && log.level !== filters.level) return false;
    if (filters.type !== 'all' && log.type !== filters.type) return false;
    if (filters.executionType !== 'all' && log.executionType !== filters.executionType) return false;
    if (filters.searchText && !log.summary.toLowerCase().includes(filters.searchText.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-info-muted to-accent-muted border-info">
        <div className="flex items-start gap-3">
          <FileText className="w-6 h-6 text-info 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">
                <Database className="w-3 h-3 mr-1" />
                完整追溯
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Shield className="w-3 h-3 mr-1" />
                审计合规
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Search className="w-3 h-3 mr-1" />
                结构化查询
              </Badge>
              <Badge variant="outline" className="bg-white">
                <History className="w-3 h-3 mr-1" />
                历史回溯
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 决策日志 */}
      <div className="space-y-6">
          {/* 统计卡片 */}
          <div className="grid grid-cols-3 gap-4">
            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">总日志数</div>
                <FileText className="w-5 h-5 text-blue-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{stats.totalLogs}</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>
                <CheckCircle className="w-5 h-5 text-green-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{stats.successRate}%</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-orange-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{stats.avgExecutionTime}s</div>
              <div className="text-xs text-muted-foreground">响应迅速</div>
            </Card>
          </div>

          {/* 筛选条件 */}
          <Card className="p-6">
            <div className="flex items-center gap-4 mb-4">
              <h3>筛选条件</h3>
            </div>

            <div className="grid grid-cols-5 gap-4">
              <div>
                <Label>执行类型</Label>
                <Select value={filters.executionType} onValueChange={(value) => setFilters({ ...filters, executionType: value as any })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="manual">👤 手动执行</SelectItem>
                    <SelectItem value="auto">⚡ 自动执行</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>状态</Label>
                <Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="success">成功</SelectItem>
                    <SelectItem value="failed">失败</SelectItem>
                    <SelectItem value="partial">部分成功</SelectItem>
                    <SelectItem value="cancelled">已取消</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>
                <Select value={filters.dateRange} onValueChange={(value) => setFilters({ ...filters, dateRange: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="today">今天</SelectItem>
                    <SelectItem value="7days">最近7天</SelectItem>
                    <SelectItem value="30days">最近30天</SelectItem>
                    <SelectItem value="all">全部</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>
          </Card>

          {/* 日志列表 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>决策日志列表</h3>
              <div className="flex gap-2">
                <Button variant="outline" size="sm">
                  <RefreshCw className="w-4 h-4 mr-2" />
                  刷新
                </Button>
              </div>
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>时间</TableHead>
                  <TableHead>执行类型</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>场景</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>耗时</TableHead>
                  <TableHead>触发人</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredLogs.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell>
                      <code className="text-xs bg-muted px-2 py-1 rounded">{log.id}</code>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">{log.timestamp}</div>
                    </TableCell>
                    <TableCell>
                      {log.executionType === 'auto' ? (
                        <Badge variant="outline" className="bg-accent/20 text-accent border-accent/40">
                          <Zap className="w-3 h-3 mr-1" />
                          自动执行
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-300">
                          <User className="w-3 h-3 mr-1" />
                          手动执行
                        </Badge>
                      )}
                      {log.executionType === 'auto' && log.trigger.conditionsMet && (
                        <div className="text-xs text-muted-foreground mt-1">
                          {log.trigger.conditionsMet}
                        </div>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{log.type}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-xs">
                        <div className="font-medium text-sm">{log.scenario}</div>
                        <div className="text-xs text-muted-foreground truncate">{log.summary}</div>
                      </div>
                    </TableCell>
                    <TableCell>{getStatusBadge(log.status)}</TableCell>
                    <TableCell>
                      <div className="text-sm">{log.executionTime}s</div>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">{log.trigger.userName}</div>
                      <div className="text-xs text-muted-foreground">{log.trigger.source}</div>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => handleViewDetail(log)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => handleViewAudit(log)}>
                          <Shield className="w-4 h-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </div>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>决策日志详情</DialogTitle>
            <DialogDescription>
              查看完整的决策生成过程和所有中间数据
            </DialogDescription>
          </DialogHeader>

          {selectedLog && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h4>基本信息</h4>
                  <div className="flex items-center gap-2">
                    {getStatusBadge(selectedLog.status)}
                    {getLevelBadge(selectedLog.level)}
                  </div>
                </div>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">日志ID</div>
                    <code className="text-xs bg-muted px-2 py-1 rounded">{selectedLog.id}</code>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">生成时间</div>
                    <div>{selectedLog.timestamp}</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">执行耗时</div>
                    <div>{selectedLog.executionTime}秒</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">决策类型</div>
                    <Badge variant="outline">{selectedLog.type}</Badge>
                  </div>
                </div>
              </div>

              <Separator />

              {/* 触发信息 */}
              <div>
                <button
                  onClick={() => toggleSection('trigger')}
                  className="flex items-center gap-2 mb-3 hover:text-info"
                >
                  {expandedSections.has('trigger') ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                  <h4>触发信息</h4>
                </button>
                {expandedSections.has('trigger') && (
                  <div className="p-4 bg-muted rounded-lg space-y-2">
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span className="text-muted-foreground">触发源：</span>
                        <span className="ml-2 font-medium">{selectedLog.trigger.source}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">触发事件：</span>
                        <span className="ml-2 font-medium">{selectedLog.trigger.event}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">用户：</span>
                        <span className="ml-2 font-medium">{selectedLog.trigger.userName}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">用户ID：</span>
                        <code className="ml-2 text-xs bg-white px-2 py-1 rounded">{selectedLog.trigger.userId}</code>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 输入数据 */}
              <div>
                <button
                  onClick={() => toggleSection('input')}
                  className="flex items-center gap-2 mb-3 hover:text-info"
                >
                  {expandedSections.has('input') ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                  <h4>输入数据明细</h4>
                  <Badge variant="outline" className="text-xs">
                    {Object.keys(selectedLog.inputData).length} 个参数
                  </Badge>
                </button>
                {expandedSections.has('input') && (
                  <div className="p-4 bg-muted rounded-lg">
                    <div className="grid grid-cols-3 gap-3 text-sm">
                      {Object.entries(selectedLog.inputData).map(([key, value]) => (
                        <div key={key} className="p-3 bg-white rounded border">
                          <div className="text-xs text-muted-foreground mb-1">{key}</div>
                          <div className="font-medium">{String(value)}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 模型服务调用 */}
              <div>
                <button
                  onClick={() => toggleSection('model')}
                  className="flex items-center gap-2 mb-3 hover:text-info"
                >
                  {expandedSections.has('model') ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                  <h4>模型服务调用</h4>
                  <Badge variant="outline" className="text-xs">
                    {selectedLog.modelService.length} 个模型
                  </Badge>
                </button>
                {expandedSections.has('model') && (
                  <div className="space-y-3">
                    {selectedLog.modelService.map((model, idx) => (
                      <div key={idx} className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                        <div className="flex items-start justify-between mb-3">
                          <div>
                            <div className="font-medium mb-1">{model.name}</div>
                            <div className="flex items-center gap-2 text-sm text-muted-foreground">
                              <Badge variant="outline" className="text-xs">v{model.version}</Badge>
                              <span>·</span>
                              <span>{model.provider}</span>
                              <span>·</span>
                              <span>耗时: {model.callTime}s</span>
                            </div>
                          </div>
                          <code className="text-xs bg-white px-2 py-1 rounded">{model.id}</code>
                        </div>
                        <div className="p-3 bg-white rounded">
                          <div className="text-xs text-muted-foreground mb-2">响应数据：</div>
                          <pre className="text-xs overflow-x-auto">
                            {JSON.stringify(model.response, null, 2)}
                          </pre>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* 执行情况 */}
              {selectedLog.execution.appliedAt && (
                <>
                  <Separator />
                  <div>
                    <h4 className="mb-3">执行情况</h4>
                    <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                      <div className="grid grid-cols-2 gap-4 text-sm mb-3">
                        <div>
                          <span className="text-muted-foreground">执行时间：</span>
                          <span className="ml-2 font-medium">{selectedLog.execution.appliedAt}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">执行人：</span>
                          <span className="ml-2 font-medium">{selectedLog.execution.appliedBy}</span>
                        </div>
                      </div>
                      {selectedLog.execution.result && (
                        <div className="p-3 bg-white rounded mb-2">
                          <div className="text-xs text-muted-foreground mb-1">执行结果：</div>
                          <div className="text-sm">{selectedLog.execution.result}</div>
                        </div>
                      )}
                      {selectedLog.execution.feedback && (
                        <div className="p-3 bg-white rounded">
                          <div className="text-xs text-muted-foreground mb-1">执行反馈：</div>
                          <div className="text-sm">{selectedLog.execution.feedback}</div>
                        </div>
                      )}
                    </div>
                  </div>
                </>
              )}
            </div>
          )}

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

      {/* 审计对话框 */}
      <Dialog open={showAuditDialog} onOpenChange={setShowAuditDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>审计追踪</DialogTitle>
            <DialogDescription>
              查看该决策的所有操作记录
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>时间</TableHead>
                  <TableHead>操作</TableHead>
                  <TableHead>用户</TableHead>
                  <TableHead>IP地址</TableHead>
                  <TableHead>详情</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {auditTrails
                  .filter(a => a.decisionId === selectedLog?.id)
                  .map((audit) => (
                    <TableRow key={audit.id}>
                      <TableCell>{audit.timestamp}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{audit.action}</Badge>
                      </TableCell>
                      <TableCell>{audit.user}</TableCell>
                      <TableCell>
                        <code className="text-xs">{audit.ipAddress}</code>
                      </TableCell>
                      <TableCell>{audit.details}</TableCell>
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          </div>

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