import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Progress } from '../ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import {
  FileText,
  Database,
  Brain,
  BookOpen,
  CheckCircle,
  AlertCircle,
  Clock,
  Download,
  ArrowRight,
  Info,
  Zap,
  Target,
  Activity,
  Settings,
  ChevronRight,
  ChevronDown,
  Calendar,
  User,
  MapPin,
  Leaf,
  Eye,
  Search,
  RefreshCw,
  Box,
  Sparkles,
  Filter,
  Power,
  Timer,
  Droplets,
  Bug,
  Sprout,
  Package,
  Layers,
  CloudRain,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';

interface AIDecisionDetailProps {
  activePath?: string;
}

// 决策来源
type DecisionSource = 'auto' | 'manual';

// 决策状态
type DecisionStatus = 'generated' | 'executing' | 'completed' | 'expired';

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

// 决策类型
type DecisionType = 'irrigation' | 'fertilizer' | 'pesticide' | 'harvest' | 'soil' | 'weather';

// 数据源
interface DataSource {
  source: string;
  timestamp: string;
  type: string;
  values: {
    [key: string]: any;
  };
}

// 模型分析
interface ModelAnalysis {
  modelId: string;
  modelName: string;
  modelVersion: string;
  provider: string;
  callTime: number;
  rawOutput: {
    [key: string]: any;
  };
  confidence: number;
  factors: {
    [key: string]: number;
  };
}

// 规则匹配
interface RuleMatch {
  ruleId: string;
  ruleName: string;
  category: string;
  priority: number;
  matched: boolean;
  confidence: number;
  conditions: {
    expression: string;
    value: any;
    expected: any;
    result: boolean;
  }[];
  calculation?: {
    formula: string;
    variables: {
      [key: string]: any;
    };
    steps: string[];
    result: any;
  };
  actions: string[];
}

// 决策列表项
interface DecisionListItem {
  id: string;
  decisionNo: string;
  title: string;
  type: DecisionType;
  source: DecisionSource; // 自动生成或手动添加
  status: DecisionStatus;
  level: DecisionLevel;
  fieldName: string;
  cropType: string;
  confidence: number;
  createdAt: string;
  createdBy: string;
  description?: string;
  // 触发条件和执行设置
  triggerCondition?: {
    device: string;
    parameter: string;
    operator: string;
    value: string;
  };
  execution?: {
    device: string;
    action: 'open' | 'close';
    duration: number;
  };
}

// 决策详情（自动生成）
interface AutoDecisionDetail {
  id: string;
  decisionNo: string;
  title: string;
  type: DecisionType;
  source: 'auto';
  status: DecisionStatus;
  level: DecisionLevel;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  
  // 基本信息
  fieldInfo: {
    fieldId: string;
    fieldName: string;
    area: number;
    cropType: string;
    growthStage: string;
    location: string;
  };
  
  // 数据快照
  dataSnapshot: DataSource[];
  
  // 模型分析
  modelAnalysis: ModelAnalysis[];
  
  // 规则匹配
  rulesMatched: RuleMatch[];
  
  // 触发条件和执行设置
  triggerCondition: {
    device: string;
    parameter: string;
    operator: string;
    value: string;
  };
  execution: {
    device: string;
    action: 'open' | 'close';
    duration: number;
  };
  
  // 最终决策
  finalDecision: {
    recommendation: string;
    parameters: {
      [key: string]: any;
    };
    expectedEffect: {
      [key: string]: string;
    };
    riskAssessment: string;
    alternatives: string[];
  };
  
  // 执行结果
  executionResult?: {
    startTime: string;
    endTime: string;
    actualEffect: {
      [key: string]: string;
    };
    deviation: string;
    evaluation: string;
  };
}

// 决策详情（手动添加）
interface ManualDecisionDetail {
  id: string;
  decisionNo: string;
  title: string;
  type: DecisionType;
  source: 'manual';
  status: DecisionStatus;
  level: DecisionLevel;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  
  // 手动输入内容
  manualInput: {
    confidence: number; // 置信度 0-1
    executionMode: 'manual' | 'auto'; // 执行模式
    recommendation: string; // 推荐建议
    explanation?: string; // 详细说明
    actionItems?: string; // 执行步骤（多行文本）
  };
  
  // 触发条件（自动执行时必填）
  triggerCondition?: {
    device: string;
    parameter: string;
    operator: string;
    value: string;
  };
  
  // 执行设置
  execution?: {
    device: string;
    action: 'open' | 'close';
    duration?: number;
  };
  
  // 执行结果
  executionResult?: {
    startTime: string;
    endTime: string;
    actualEffect: {
      [key: string]: string;
    };
    evaluation: string;
  };
}

export function AIDecisionDetail({ activePath }: AIDecisionDetailProps) {
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedDecision, setSelectedDecision] = useState<DecisionListItem | null>(null);
  const [expandedSections, setExpandedSections] = useState<Set<string>>(
    new Set(['snapshot', 'model', 'rules', 'decision'])
  );

  // 筛选条件
  const [filters, setFilters] = useState({
    source: 'all',
    type: 'all',
    status: 'all',
    level: 'all',
    field: 'all',
    cropType: 'all',
    dateRange: '7days',
    searchText: '',
  });

  // 模拟决策列表数据（包含自动生成和手动添加）
  const [decisions] = useState<DecisionListItem[]>([
    // 自动生成决策 #1
    {
      id: 'dec_001',
      decisionNo: 'DEC-20241023-001',
      title: '1号大棚番茄开花期灌溉',
      description: '土壤湿度35%，低于最佳湿度，建议立即灌溉120升',
      type: 'irrigation',
      source: 'auto',
      status: 'completed',
      level: 'important',
      fieldName: '1号大棚',
      cropType: '番茄',
      confidence: 0.89,
      createdAt: '2024-10-23 14:30',
      createdBy: '系统自动生成',
      triggerCondition: {
        device: '土壤传感器-01',
        parameter: '土壤湿度',
        operator: '<',
        value: '30',
      },
      execution: {
        device: '水肥机-01',
        action: 'open',
        duration: 45,
      },
    },
    // 手动添加决策 #1
    {
      id: 'dec_002',
      decisionNo: 'DEC-20241023-002',
      title: '2号大棚温度控制',
      description: '预计下午温度过高，需要开启通风设备降温',
      type: 'weather',
      source: 'manual',
      status: 'executing',
      level: 'normal',
      fieldName: '2号大棚',
      cropType: '番茄',
      confidence: 0.86,
      createdAt: '2024-10-23 12:15',
      createdBy: '张三',
      triggerCondition: {
        device: '温度传感器-02',
        parameter: '空气温度',
        operator: '>',
        value: '35',
      },
      execution: {
        device: '排风扇-02',
        action: 'open',
        duration: 20,
      },
    },
    // 自动生成决策 #2
    {
      id: 'dec_003',
      decisionNo: 'DEC-20241022-003',
      title: '3号地块小麦结实期追肥',
      description: '检测到土壤氮磷钾含量偏低，建议施用复合肥提升产量',
      type: 'fertilizer',
      source: 'auto',
      status: 'completed',
      level: 'important',
      fieldName: '3号地块',
      cropType: '小麦',
      confidence: 0.92,
      createdAt: '2024-10-22 09:30',
      createdBy: '系统自动生成',
    },
    // 手动添加决策 #2
    {
      id: 'dec_004',
      decisionNo: 'DEC-20241021-004',
      title: '4号地块土壤pH调节',
      description: 'pH值偏低，建议施用石灰调节土壤酸碱度',
      type: 'soil',
      source: 'manual',
      status: 'completed',
      level: 'normal',
      fieldName: '4号地块',
      cropType: '玉米',
      confidence: 0.85,
      createdAt: '2024-10-21 15:00',
      createdBy: '李四',
    },
    // 自动生成决策 #3
    {
      id: 'dec_005',
      decisionNo: 'DEC-20241023-005',
      title: '5号地块水稻收获时机',
      description: '水稻已达到成熟期，湿度和天气条件适宜，建议3天内完成收获',
      type: 'harvest',
      source: 'auto',
      status: 'generated',
      level: 'critical',
      fieldName: '5号地块',
      cropType: '水稻',
      confidence: 0.94,
      createdAt: '2024-10-23 08:00',
      createdBy: '系统自动生成',
    },
    // 手动添加决策 #3
    {
      id: 'dec_006',
      decisionNo: 'DEC-20241023-006',
      title: '6号大棚黄瓜病虫害防治',
      description: '发现蚜虫初期感染迹象，建议使用生物防治剂进行预防',
      type: 'pesticide',
      source: 'manual',
      status: 'generated',
      level: 'important',
      fieldName: '6号大棚',
      cropType: '黄瓜',
      confidence: 0.78,
      createdAt: '2024-10-23 16:45',
      createdBy: '王五',
    },
    // 自动生成决策 #4
    {
      id: 'dec_007',
      decisionNo: 'DEC-20241022-007',
      title: '7号大棚茄子灌溉补充',
      description: '连续3天无降雨，土壤湿度下降至42%，建议补充灌溉',
      type: 'irrigation',
      source: 'auto',
      status: 'completed',
      level: 'normal',
      fieldName: '7号大棚',
      cropType: '茄子',
      confidence: 0.87,
      createdAt: '2024-10-22 18:20',
      createdBy: '系统自动生成',
      triggerCondition: {
        device: '土壤传感器-07',
        parameter: '土壤湿度',
        operator: '<',
        value: '45',
      },
      execution: {
        device: '水肥机-07',
        action: 'open',
        duration: 30,
      },
    },
    // 自动生成决策 #5
    {
      id: 'dec_008',
      decisionNo: 'DEC-20241020-008',
      title: '8号地块玉米病害预警',
      description: 'AI模型检测到叶斑病早期特征，建议立即喷洒防治药剂',
      type: 'pesticide',
      source: 'auto',
      status: 'expired',
      level: 'critical',
      fieldName: '8号地块',
      cropType: '玉米',
      confidence: 0.91,
      createdAt: '2024-10-20 10:30',
      createdBy: '系统自动生成',
    },
    // 手动添加决策 #4
    {
      id: 'dec_009',
      decisionNo: 'DEC-20241023-009',
      title: '9号大棚辣椒生长调控',
      description: '根据经验判断需要增加光照和通风，促进果实发育',
      type: 'weather',
      source: 'manual',
      status: 'executing',
      level: 'suggestion',
      fieldName: '9号大棚',
      cropType: '辣椒',
      confidence: 0.75,
      createdAt: '2024-10-23 13:00',
      createdBy: '赵六',
      triggerCondition: {
        device: '光照传感器-09',
        parameter: '光照强度',
        operator: '<',
        value: '10000',
      },
      execution: {
        device: '补光灯-09',
        action: 'open',
        duration: 180,
      },
    },
    // 自动生成决策 #6
    {
      id: 'dec_010',
      decisionNo: 'DEC-20241023-010',
      title: '10号地块大豆补充施肥',
      description: '开花期氮肥需求增加，建议追施尿素促进生长',
      type: 'fertilizer',
      source: 'auto',
      status: 'generated',
      level: 'important',
      fieldName: '10号地块',
      cropType: '大豆',
      confidence: 0.88,
      createdAt: '2024-10-23 11:15',
      createdBy: '系统自动生成',
    },
    // 手动添加决策 #5
    {
      id: 'dec_011',
      decisionNo: 'DEC-20241022-011',
      title: '11号大棚草莓土壤改良',
      description: '观察到土壤板结现象，建议添加有机肥改善土壤结构',
      type: 'soil',
      source: 'manual',
      status: 'completed',
      level: 'normal',
      fieldName: '11号大棚',
      cropType: '草莓',
      confidence: 0.82,
      createdAt: '2024-10-22 14:30',
      createdBy: '孙七',
    },
    // 自动生成决策 #7
    {
      id: 'dec_012',
      decisionNo: 'DEC-20241021-012',
      title: '12号地块花生收获建议',
      description: '根据生长周期和成熟度检测，建议10天内安排收获作业',
      type: 'harvest',
      source: 'auto',
      status: 'completed',
      level: 'important',
      fieldName: '12号地块',
      cropType: '花生',
      confidence: 0.90,
      createdAt: '2024-10-21 09:00',
      createdBy: '系统自动生成',
    },
    // 手动添加决策 #6
    {
      id: 'dec_013',
      decisionNo: 'DEC-20241023-013',
      title: '13号大棚西红柿防寒措施',
      description: '天气预报显示未来降温，建议提前做好保温准备',
      type: 'weather',
      source: 'manual',
      status: 'generated',
      level: 'important',
      fieldName: '13号大棚',
      cropType: '西红柿',
      confidence: 0.80,
      createdAt: '2024-10-23 17:20',
      createdBy: '周八',
    },
    // 自动生成决策 #8
    {
      id: 'dec_014',
      decisionNo: 'DEC-20241023-014',
      title: '14号大棚黄瓜精准灌溉',
      description: 'AI模型预测未来3天需水量，建议分段灌溉优化水分利用',
      type: 'irrigation',
      source: 'auto',
      status: 'generated',
      level: 'normal',
      fieldName: '14号大棚',
      cropType: '黄瓜',
      confidence: 0.86,
      createdAt: '2024-10-23 15:40',
      createdBy: '系统自动生成',
      triggerCondition: {
        device: '土壤传感器-14',
        parameter: '土壤湿度',
        operator: '<',
        value: '50',
      },
      execution: {
        device: '水肥机-14',
        action: 'open',
        duration: 25,
      },
    },
    // 自动生成决策 #9
    {
      id: 'dec_015',
      decisionNo: 'DEC-20241022-015',
      title: '15号地块芹菜病虫害监测',
      description: '图像识别发现潜叶蝇活动迹象，建议使用黄板诱捕',
      type: 'pesticide',
      source: 'auto',
      status: 'executing',
      level: 'suggestion',
      fieldName: '15号地块',
      cropType: '芹菜',
      confidence: 0.79,
      createdAt: '2024-10-22 16:10',
      createdBy: '系统自动生成',
    },
  ]);

  // 模拟自动生成决策的完整详情
  const autoDecisionDetail: AutoDecisionDetail = {
    id: 'dec_001',
    decisionNo: 'DEC-20241023-001',
    title: '1号大棚番茄开花期灌溉',
    type: 'irrigation',
    source: 'auto',
    status: 'completed',
    level: 'important',
    createdAt: '2024-10-23 14:30:25',
    updatedAt: '2024-10-23 17:10:00',
    createdBy: '系统自动生成',
    
    fieldInfo: {
      fieldId: 'field_001',
      fieldName: '1号大棚',
      area: 2.5,
      cropType: '番茄',
      growthStage: '开花期',
      location: '北京市昌平区',
    },
    
    dataSnapshot: [
      {
        source: '土壤传感器-01',
        timestamp: '2024-10-23 14:28:00',
        type: '传感器数据',
        values: {
          土壤湿度: '35%',
          土壤温度: '18℃',
          土壤EC值: '1.2 mS/cm',
          土壤pH值: '6.8',
        },
      },
      {
        source: '气象站-001',
        timestamp: '2024-10-23 14:28:00',
        type: '气象数据',
        values: {
          气温: '28℃',
          空气湿度: '65%',
          风速: '2.5 m/s',
          光照强度: '15000 lux',
        },
      },
      {
        source: '天气预报服务',
        timestamp: '2024-10-23 14:28:00',
        type: '预报数据',
        values: {
          未来3天天气: '晴天',
          降雨概率: '10%',
          最高气温: '30℃',
          最低气温: '18℃',
        },
      },
      {
        source: '灌溉记录数据库',
        timestamp: '2024-10-23 14:28:00',
        type: '历史数据',
        values: {
          上次灌溉时间: '2024-10-20 18:00',
          上次灌溉量: '100升',
          距今天数: '3天',
        },
      },
    ],
    
    modelAnalysis: [
      {
        modelId: 'model_001',
        modelName: '作物需水预测模型',
        modelVersion: 'v2.1.3',
        provider: 'AgriAI',
        callTime: 0.8,
        rawOutput: {
          预测需水量: '120升',
          日均耗水量: '40升',
          最佳湿度: '65%',
          当前缺水: '30%',
          紧急程度: '高',
        },
        confidence: 0.92,
        factors: {
          生长阶段: 0.85,
          天气条件: 0.78,
          土壤状态: 0.88,
          历史模式: 0.90,
        },
      },
      {
        modelId: 'model_002',
        modelName: '灌溉时机优化模型',
        modelVersion: 'v1.5.0',
        provider: 'AgriAI',
        callTime: 0.5,
        rawOutput: {
          最佳时间: '17:00-18:00',
          理由: '避开高温时段，减少蒸发',
          温度预测: '26℃',
          蒸发率: '0.15',
          吸收率: '0.92',
        },
        confidence: 0.88,
        factors: {
          温度预测: 0.90,
          蒸发量: 0.85,
          吸收效率: 0.92,
        },
      },
    ],
    
    rulesMatched: [
      {
        ruleId: 'rule_001',
        ruleName: '开花期灌溉规则',
        category: '生长期管理',
        priority: 9,
        matched: true,
        confidence: 0.95,
        conditions: [
          {
            expression: '生长阶段 == "开花期"',
            value: '开花期',
            expected: '开花期',
            result: true,
          },
          {
            expression: '土壤湿度 < 40%',
            value: 35,
            expected: '< 40',
            result: true,
          },
          {
            expression: '距上次灌溉 > 2天',
            value: 3,
            expected: '> 2',
            result: true,
          },
        ],
        calculation: {
          formula: '灌溉量 = (目标湿度 - 当前湿度) × 地块面积 × 系数',
          variables: {
            目标湿度: 65,
            当前湿度: 35,
            地块面积: 2.5,
            系数: 0.8,
          },
          steps: [
            '1. 计算湿度差：65 - 35 = 30',
            '2. 乘以地块面积：30 × 2.5 = 75',
            '3. 乘以调整系数：75 × 0.8 = 60',
            '4. 考虑安全裕度：60 × 2 = 120升',
          ],
          result: '120升',
        },
        actions: [
          '开启灌溉系统',
          '控制灌溉量为120升',
          '选择傍晚时段（17:00-18:00）',
          '监控土壤湿度变化',
        ],
      },
      {
        ruleId: 'rule_002',
        ruleName: '节水灌溉规则',
        category: '资源优化',
        priority: 7,
        matched: true,
        confidence: 0.88,
        conditions: [
          {
            expression: '未来3天无降雨',
            value: true,
            expected: true,
            result: true,
          },
          {
            expression: '蒸发率 < 0.2',
            value: 0.15,
            expected: '< 0.2',
            result: true,
          },
        ],
        actions: [
          '选择低蒸发时段',
          '采用滴灌方式',
          '分段灌溉',
        ],
      },
    ],
    
    triggerCondition: {
      device: '土壤传感器-01',
      parameter: '土壤湿度',
      operator: '<',
      value: '30',
    },
    execution: {
      device: '水肥机-01',
      action: 'open',
      duration: 45,
    },
    
    finalDecision: {
      recommendation: '建议在今日17:00开启灌溉系统，灌溉量120升，预计45分钟完成',
      parameters: {
        灌溉量: '120升',
        灌溉时间: '17:00-17:45',
        灌溉方式: '滴灌',
        流量: '2.67升/分钟',
      },
      expectedEffect: {
        土壤湿度: '从35%提升至65%',
        土壤温度: '保持在18-20℃',
        作物状态: '缓解水分胁迫，促进开花结果',
        预计产量提升: '8-12%',
      },
      riskAssessment: '风险较低。天气条件良好，蒸发损失可控。需注意监控土壤湿度，避免过度灌溉导致根部缺氧。',
      alternatives: [
        '方案B：分两次灌溉，每次60升，间隔12小时',
        '方案C：等待明日早晨灌溉，但可能影响当天作物生长',
        '方案D：减少灌溉量至80升，2天后再次评估',
      ],
    },
    
    executionResult: {
      startTime: '2024-10-23 17:00:00',
      endTime: '2024-10-23 17:43:00',
      actualEffect: {
        土壤湿度: '从35%提升至63%（目标65%）',
        实际灌溉量: '118升',
        吸收率: '92%',
        蒸发损失: '2升（1.7%）',
      },
      deviation: '实际湿度提升至63%，略低于目标65%，但在可接受范围内',
      evaluation: '执行效果良好。实际用水118升，比预期节省2升。土壤湿度达到预期的97%，满足番茄开花期需求。建议2天后再次评估。',
    },
  };

  // 模拟手动添加决策的完整详情
  const manualDecisionDetail: ManualDecisionDetail = {
    id: 'dec_002',
    decisionNo: 'DEC-20241023-002',
    title: '2号大棚温度控制',
    type: 'weather',
    source: 'manual',
    status: 'executing',
    level: 'normal',
    createdAt: '2024-10-23 12:15:30',
    updatedAt: '2024-10-23 12:15:30',
    createdBy: '张三',
    
    manualInput: {
      confidence: 0.86,
      executionMode: 'auto',
      
      recommendation: '预计下午温度过高，建议立即启动通风降温系统，打开排风扇进行强制通风，同时启用遮阳网减少光照强度',
      
      explanation: `当前情况分析：

天气预报显示今日下午最高温度将达到37℃，远超番茄生长适宜温度（22-28℃），可能导致高温胁迫。

当前观察情况：
- 大棚内温度：32℃（上午11:00测量）
- 外界温度：35℃  
- 空气湿度：55%
- 部分叶片出现卷曲现象
- 花朵开始萎蔫

风险评估：
如不及时降温，可能导致花粉活力下降、落花落果，影响产量10-20%。高温持续超过2小时可能造成不可逆损伤。

预期效果：
通过排风扇通风和遮阳网遮阳，预计可将大棚温度降至28℃左右的适宜范围`,
      
      actionItems: `立即开启排风扇进行通风降温，设置3档最大风量
拉开遮阳网，遮阳率设置为60%
适当喷雾增湿，降低叶面温度，每30分钟喷雾一次
持续监控温度变化，每15分钟记录一次
如温度仍高于30℃，补充喷灌降温
运行20分钟后评估效果，根据情况调整`,
    },
    
    triggerCondition: {
      device: '温度传感器-02',
      parameter: '空气温度',
      operator: '>',
      value: '35',
    },
    execution: {
      device: '排风扇-02',
      action: 'open',
      duration: 20,
    },
    
    executionResult: {
      startTime: '2024-10-23 12:30:00',
      endTime: '2024-10-23 12:50:00',
      actualEffect: {
        大棚温度: '从32℃降至28℃',
        空气湿度: '从55%提升至62%',
        叶片状态: '卷曲现象明显改善',
        花朵状态: '恢复正常',
      },
      evaluation: '降温措施有效，大棚温度成功控制在适宜范围内。叶片和花朵状态恢复良好，避免了高温胁迫损害。',
    },
  };

  // 应用筛选条件
  const filteredDecisions = decisions.filter(decision => {
    if (filters.source !== 'all' && decision.source !== filters.source) return false;
    if (filters.type !== 'all' && decision.type !== filters.type) return false;
    if (filters.status !== 'all' && decision.status !== filters.status) return false;
    if (filters.level !== 'all' && decision.level !== filters.level) return false;
    if (filters.field !== 'all' && decision.fieldName !== filters.field) return false;
    if (filters.cropType !== 'all' && decision.cropType !== filters.cropType) return false;
    if (filters.searchText && !decision.title.toLowerCase().includes(filters.searchText.toLowerCase())) return false;
    
    return true;
  });

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

  const handleViewDetail = (decision: DecisionListItem) => {
    setSelectedDecision(decision);
    setShowDetailDialog(true);
  };

  const handleRefresh = () => {
    toast.success('数据已刷新');
  };

  const handleExport = () => {
    toast.success('决策详情导出成功');
  };

  const getSourceBadge = (source: DecisionSource) => {
    const config = {
      auto: { label: '自动生成', className: 'bg-accent-muted text-accent-foreground border-accent', icon: Sparkles },
      manual: { label: '手动添加', className: 'bg-info-muted text-info-muted-foreground border-info', icon: User },
    };
    const { label, className, icon: Icon } = config[source];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getTypeBadge = (type: DecisionType) => {
    const config = {
      irrigation: { label: '灌溉', icon: Droplets, className: 'bg-info-muted text-info-muted-foreground' },
      fertilizer: { label: '施肥', icon: Sprout, className: 'bg-success-muted text-success-muted-foreground' },
      pesticide: { label: '打药', icon: Bug, className: 'bg-warning-muted text-warning-muted-foreground' },
      harvest: { label: '收获', icon: Package, className: 'bg-accent-muted text-accent-foreground' },
      soil: { label: '土壤', icon: Layers, className: 'bg-warning-muted text-warning-muted-foreground' },
      weather: { label: '气象', icon: CloudRain, className: 'bg-info-muted text-info-muted-foreground' },
    };
    const { label, icon: Icon, className } = config[type];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getStatusBadge = (status: DecisionStatus) => {
    const config = {
      generated: { label: '已生成', icon: Sparkles, className: 'bg-info-muted text-info-muted-foreground border-info' },
      executing: { label: '执行中', icon: Activity, className: 'bg-accent-muted text-accent-foreground border-accent' },
      completed: { label: '已完成', icon: CheckCircle, className: 'bg-success-muted text-success-muted-foreground border-success' },
      expired: { label: '已过期', icon: Clock, 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-foreground border-error' },
      important: { label: '重要', className: 'bg-warning-muted text-warning-foreground border-warning' },
      normal: { label: '一般', className: 'bg-info-muted text-info-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 stats = {
    total: decisions.length,
    auto: decisions.filter(d => d.source === 'auto').length,
    manual: decisions.filter(d => d.source === 'manual').length,
    generated: decisions.filter(d => d.status === 'generated').length,
    executing: decisions.filter(d => d.status === 'executing').length,
    completed: decisions.filter(d => d.status === 'completed').length,
  };

  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 justify-between">
          <div className="flex items-start gap-3">
            <FileText className="w-6 h-6 text-success flex-shrink-0 mt-1" />
            <div className="flex-1">
              <h2 className="mb-2">决策详情</h2>
              <p className="text-sm text-muted-foreground mb-3">
                查看AI自动生成和用户手动添加的决策完整信息，包括数据来源、分析过程和执行结果
              </p>
              <div className="flex flex-wrap gap-2">
                <Badge variant="outline" className="bg-white">
                  <Sparkles className="w-3 h-3 mr-1" />
                  AI自动生成
                </Badge>
                <Badge variant="outline" className="bg-white">
                  <User className="w-3 h-3 mr-1" />
                  用户手动添加
                </Badge>
                <Badge variant="outline" className="bg-white">
                  <Database 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>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={handleRefresh}>
              <RefreshCw className="w-4 h-4 mr-1" />
              刷新
            </Button>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-5 gap-4">
        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">总决策数</div>
            <FileText className="w-4 h-4 text-gray-400" />
          </div>
          <div className="text-2xl font-bold">{stats.total}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">自动生成</div>
            <Sparkles className="w-4 h-4 text-purple-500" />
          </div>
          <div className="text-2xl font-bold text-accent">{stats.auto}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">手动添加</div>
            <User className="w-4 h-4 text-blue-500" />
          </div>
          <div className="text-2xl font-bold text-info">{stats.manual}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">执行中</div>
            <Activity className="w-4 h-4 text-purple-500" />
          </div>
          <div className="text-2xl font-bold text-accent">{stats.executing}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">已完成</div>
            <CheckCircle className="w-4 h-4 text-green-500" />
          </div>
          <div className="text-2xl font-bold text-success">{stats.completed}</div>
        </Card>
      </div>

      {/* 筛选工具栏 */}
      <Card className="p-4">
        <div className="flex items-center gap-2 mb-4">
          <Filter className="w-5 h-5 text-success" />
          <h3>筛选条件</h3>
        </div>
        <div className="flex items-center gap-4 flex-wrap">
          {/* 搜索 */}
          <div className="flex-1 min-w-64">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder="搜索决策标题..."
                value={filters.searchText}
                onChange={(e) => setFilters({ ...filters, searchText: e.target.value })}
                className="pl-10"
              />
            </div>
          </div>

          {/* 决策来源 */}
          <div className="w-40">
            <Select value={filters.source} onValueChange={(value) => setFilters({ ...filters, source: value })}>
              <SelectTrigger>
                <SelectValue placeholder="决策来源" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部来源</SelectItem>
                <SelectItem value="auto">自动生成</SelectItem>
                <SelectItem value="manual">手动添加</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 决策类型 */}
          <div className="w-40">
            <Select value={filters.type} onValueChange={(value) => setFilters({ ...filters, type: value })}>
              <SelectTrigger>
                <SelectValue placeholder="决策类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                <SelectItem value="irrigation">灌溉</SelectItem>
                <SelectItem value="fertilizer">施肥</SelectItem>
                <SelectItem value="pesticide">打药</SelectItem>
                <SelectItem value="harvest">收获</SelectItem>
                <SelectItem value="soil">土壤</SelectItem>
                <SelectItem value="weather">气象</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 决策状态 */}
          <div className="w-40">
            <Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
              <SelectTrigger>
                <SelectValue placeholder="决策状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="generated">已生成</SelectItem>
                <SelectItem value="executing">执行中</SelectItem>
                <SelectItem value="completed">已完成</SelectItem>
                <SelectItem value="expired">已过期</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 决策级别 */}
          <div className="w-40">
            <Select value={filters.level} onValueChange={(value) => setFilters({ ...filters, level: value })}>
              <SelectTrigger>
                <SelectValue placeholder="决策级别" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部级别</SelectItem>
                <SelectItem value="critical">紧急</SelectItem>
                <SelectItem value="important">重要</SelectItem>
                <SelectItem value="normal">一般</SelectItem>
                <SelectItem value="suggestion">建议</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* 筛选结果提示 */}
        <div className="mt-3 flex items-center gap-2 text-sm text-muted-foreground">
          <Info className="w-4 h-4" />
          共找到 <strong className="text-foreground">{filteredDecisions.length}</strong> 条决策
        </div>
      </Card>

      {/* 决策列表 */}
      <Card className="p-6">
        <h3 className="mb-4">决策列表</h3>
        
        {filteredDecisions.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <FileText className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <div>暂无符合条件的决策</div>
          </div>
        ) : (
          <div className="space-y-4">
            {filteredDecisions.map((decision) => (
              <Card key={decision.id} className="p-5 hover:shadow-md transition-shadow">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      {getSourceBadge(decision.source)}
                      {getTypeBadge(decision.type)}
                      {getStatusBadge(decision.status)}
                      {getLevelBadge(decision.level)}
                    </div>
                    
                    <h4 className="mb-2">{decision.title}</h4>
                    
                    {decision.description && (
                      <p className="text-sm text-muted-foreground mb-3">
                        {decision.description}
                      </p>
                    )}

                    <div className="grid grid-cols-4 gap-4 text-sm">
                      <div>
                        <span className="text-muted-foreground">决策编号:</span>
                        <span className="ml-2 font-medium">{decision.decisionNo}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">地块:</span>
                        <span className="ml-2 font-medium">{decision.fieldName}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">作物:</span>
                        <span className="ml-2 font-medium">{decision.cropType}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">创建时间:</span>
                        <span className="ml-2 font-medium">{decision.createdAt}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">创建人:</span>
                        <span className="ml-2 font-medium">{decision.createdBy}</span>
                      </div>
                      {decision.source === 'auto' && (
                        <div>
                          <span className="text-muted-foreground">置信度:</span>
                          <span className="ml-2 font-medium">{(decision.confidence * 100).toFixed(0)}%</span>
                        </div>
                      )}
                    </div>

                    {/* 触发条件和执行设置 */}
                    {decision.triggerCondition && decision.execution && (
                      <div className="mt-3 p-3 bg-info/10 rounded-lg border border-info/30">
                        <div className="grid grid-cols-2 gap-3 text-sm">
                          <div>
                            <div className="text-muted-foreground mb-1">触发条件</div>
                            <div className="font-medium">
                              {decision.triggerCondition.device} - {decision.triggerCondition.parameter} {decision.triggerCondition.operator} {decision.triggerCondition.value}
                            </div>
                          </div>
                          <div>
                            <div className="text-muted-foreground mb-1">执行设置</div>
                            <div className="font-medium">
                              {decision.execution.device} - {decision.execution.action === 'open' ? '开启' : '关闭'} ({decision.execution.duration}分钟)
                            </div>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>

                  <div className="ml-4">
                    <Button size="sm" variant="outline" onClick={() => handleViewDetail(decision)}>
                      <Eye className="w-4 h-4 mr-1" />
                      查看详情
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </Card>

      {/* 决策详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedDecision && (
                <div className="flex items-center gap-2">
                  <span>{selectedDecision.title}</span>
                  {getSourceBadge(selectedDecision.source)}
                </div>
              )}
            </DialogTitle>
            <DialogDescription>
              查看决策的完整分析过程和执行详情
            </DialogDescription>
          </DialogHeader>

          {selectedDecision && (
            <Tabs defaultValue={selectedDecision.source === 'auto' ? 'auto' : 'manual'} className="mt-4">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="auto" disabled={selectedDecision.source !== 'auto'}>
                  自动生成详情
                </TabsTrigger>
                <TabsTrigger value="manual" disabled={selectedDecision.source !== 'manual'}>
                  手动添加详情
                </TabsTrigger>
              </TabsList>

              {/* 自动生成决策详情 */}
              <TabsContent value="auto" className="space-y-6">
                {/* 基本信息 */}
                <Card className="p-4">
                  <h4 className="mb-3">基本信息</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <div className="text-muted-foreground mb-1">决策编号</div>
                      <div className="font-medium">{autoDecisionDetail.decisionNo}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">地块名称</div>
                      <div className="font-medium">{autoDecisionDetail.fieldInfo.fieldName}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">作物类型</div>
                      <div className="font-medium">{autoDecisionDetail.fieldInfo.cropType}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">生长阶段</div>
                      <div className="font-medium">{autoDecisionDetail.fieldInfo.growthStage}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">地块面积</div>
                      <div className="font-medium">{autoDecisionDetail.fieldInfo.area}亩</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">位置</div>
                      <div className="font-medium">{autoDecisionDetail.fieldInfo.location}</div>
                    </div>
                  </div>
                </Card>

                {/* 数据快照 */}
                <Card className="p-4">
                  <button
                    onClick={() => toggleSection('snapshot')}
                    className="w-full flex items-center justify-between mb-3"
                  >
                    <h4>数据快照</h4>
                    {expandedSections.has('snapshot') ? (
                      <ChevronDown className="w-5 h-5" />
                    ) : (
                      <ChevronRight className="w-5 h-5" />
                    )}
                  </button>
                  {expandedSections.has('snapshot') && (
                    <div className="space-y-3">
                      {autoDecisionDetail.dataSnapshot.map((data, idx) => (
                        <div key={idx} className="p-3 bg-muted rounded">
                          <div className="flex items-center justify-between mb-2">
                            <div className="flex items-center gap-2">
                              <Database className="w-4 h-4 text-info" />
                              <strong className="text-sm">{data.source}</strong>
                            </div>
                            <Badge variant="outline" className="text-xs">{data.type}</Badge>
                          </div>
                          <div className="text-xs text-muted-foreground mb-2">{data.timestamp}</div>
                          <div className="grid grid-cols-4 gap-2 text-sm">
                            {Object.entries(data.values).map(([key, value]) => (
                              <div key={key}>
                                <span className="text-muted-foreground">{key}:</span>
                                <strong className="ml-1">{String(value)}</strong>
                              </div>
                            ))}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </Card>

                {/* 模型分析 */}
                <Card className="p-4">
                  <button
                    onClick={() => toggleSection('model')}
                    className="w-full flex items-center justify-between mb-3"
                  >
                    <h4>AI模型分析</h4>
                    {expandedSections.has('model') ? (
                      <ChevronDown className="w-5 h-5" />
                    ) : (
                      <ChevronRight className="w-5 h-5" />
                    )}
                  </button>
                  {expandedSections.has('model') && (
                    <div className="space-y-4">
                      {autoDecisionDetail.modelAnalysis.map((model, idx) => (
                        <div key={idx} className="p-4 bg-accent/20 rounded border border-accent/40">
                          <div className="flex items-center justify-between mb-3">
                            <div className="flex items-center gap-2">
                              <Brain className="w-5 h-5 text-accent" />
                              <strong>{model.modelName}</strong>
                            </div>
                            <div className="flex items-center gap-4 text-sm">
                              <span className="text-muted-foreground">
                                版本: {model.modelVersion}
                              </span>
                              <span className="text-muted-foreground">
                                耗时: {model.callTime}s
                              </span>
                              <Badge variant="outline" className="bg-white">
                                置信度: {(model.confidence * 100).toFixed(0)}%
                              </Badge>
                            </div>
                          </div>

                          <div className="grid grid-cols-2 gap-4 mb-3">
                            <div>
                              <div className="text-sm text-muted-foreground mb-2">模型输出</div>
                              <div className="p-3 bg-white rounded text-sm space-y-1">
                                {Object.entries(model.rawOutput).map(([key, value]) => (
                                  <div key={key}>
                                    <span className="text-muted-foreground">{key}:</span>
                                    <strong className="ml-2">{String(value)}</strong>
                                  </div>
                                ))}
                              </div>
                            </div>
                            <div>
                              <div className="text-sm text-muted-foreground mb-2">影响因子</div>
                              <div className="space-y-2">
                                {Object.entries(model.factors).map(([key, value]) => (
                                  <div key={key}>
                                    <div className="flex items-center justify-between text-sm mb-1">
                                      <span>{key}</span>
                                      <span className="font-medium">{(value * 100).toFixed(0)}%</span>
                                    </div>
                                    <Progress value={value * 100} className="h-2" />
                                  </div>
                                ))}
                              </div>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </Card>

                {/* 规则匹配 */}
                <Card className="p-4">
                  <button
                    onClick={() => toggleSection('rules')}
                    className="w-full flex items-center justify-between mb-3"
                  >
                    <h4>规则匹配结果</h4>
                    {expandedSections.has('rules') ? (
                      <ChevronDown className="w-5 h-5" />
                    ) : (
                      <ChevronRight className="w-5 h-5" />
                    )}
                  </button>
                  {expandedSections.has('rules') && (
                    <div className="space-y-4">
                      {autoDecisionDetail.rulesMatched.map((rule, idx) => (
                        <div key={idx} className="p-4 bg-success/10 rounded border border-success/30">
                          <div className="flex items-center justify-between mb-3">
                            <div className="flex items-center gap-2">
                              <BookOpen className="w-5 h-5 text-success" />
                              <strong>{rule.ruleName}</strong>
                            </div>
                            <div className="flex items-center gap-2">
                              <Badge variant="outline">{rule.category}</Badge>
                              <Badge variant="outline">优先级: {rule.priority}</Badge>
                              <Badge variant="outline" className="bg-white">
                                置信度: {(rule.confidence * 100).toFixed(0)}%
                              </Badge>
                            </div>
                          </div>

                          <div className="mb-3">
                            <div className="text-sm text-muted-foreground mb-2">匹配条件</div>
                            <div className="space-y-1">
                              {rule.conditions.map((cond, i) => (
                                <div key={i} className="flex items-center gap-2 text-sm p-2 bg-white rounded">
                                  {cond.result ? (
                                    <CheckCircle className="w-4 h-4 text-success" />
                                  ) : (
                                    <AlertCircle className="w-4 h-4 text-destructive" />
                                  )}
                                  <code className="flex-1">{cond.expression}</code>
                                  <span className="text-muted-foreground">
                                    值: {String(cond.value)}
                                  </span>
                                </div>
                              ))}
                            </div>
                          </div>

                          {rule.calculation && (
                            <div className="mb-3">
                              <div className="text-sm text-muted-foreground mb-2">计算过程</div>
                              <div className="p-3 bg-white rounded">
                                <div className="font-mono text-sm mb-2">{rule.calculation.formula}</div>
                                <div className="text-xs text-muted-foreground mb-2">变量:</div>
                                <div className="grid grid-cols-4 gap-2 text-xs mb-2">
                                  {Object.entries(rule.calculation.variables).map(([key, value]) => (
                                    <div key={key}>
                                      {key} = {String(value)}
                                    </div>
                                  ))}
                                </div>
                                <div className="text-xs text-muted-foreground mb-1">步骤:</div>
                                <div className="space-y-1 text-xs">
                                  {rule.calculation.steps.map((step, i) => (
                                    <div key={i} className="font-mono">{step}</div>
                                  ))}
                                </div>
                                <div className="mt-2 pt-2 border-t">
                                  <strong className="text-sm">结果: {String(rule.calculation.result)}</strong>
                                </div>
                              </div>
                            </div>
                          )}

                          <div>
                            <div className="text-sm text-muted-foreground mb-2">执行动作</div>
                            <div className="flex flex-wrap gap-2">
                              {rule.actions.map((action, i) => (
                                <Badge key={i} variant="outline" className="bg-white">
                                  <Zap className="w-3 h-3 mr-1" />
                                  {action}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </Card>

                {/* 最终决策 */}
                <Card className="p-4">
                  <button
                    onClick={() => toggleSection('decision')}
                    className="w-full flex items-center justify-between mb-3"
                  >
                    <h4>最终决策建议</h4>
                    {expandedSections.has('decision') ? (
                      <ChevronDown className="w-5 h-5" />
                    ) : (
                      <ChevronRight className="w-5 h-5" />
                    )}
                  </button>
                  {expandedSections.has('decision') && (
                    <div className="space-y-4">
                      <div className="p-4 bg-info/10 rounded border border-info/30">
                        <div className="flex items-center gap-2 mb-2">
                          <Target className="w-5 h-5 text-info" />
                          <strong>决策建议</strong>
                        </div>
                        <p className="text-sm">{autoDecisionDetail.finalDecision.recommendation}</p>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <div className="text-sm text-muted-foreground mb-2">执行参数</div>
                          <div className="p-3 bg-muted rounded space-y-1 text-sm">
                            {Object.entries(autoDecisionDetail.finalDecision.parameters).map(([key, value]) => (
                              <div key={key}>
                                <span className="text-muted-foreground">{key}:</span>
                                <strong className="ml-2">{String(value)}</strong>
                              </div>
                            ))}
                          </div>
                        </div>
                        <div>
                          <div className="text-sm text-muted-foreground mb-2">预期效果</div>
                          <div className="p-3 bg-success/10 rounded space-y-1 text-sm">
                            {Object.entries(autoDecisionDetail.finalDecision.expectedEffect).map(([key, value]) => (
                              <div key={key}>
                                <span className="text-muted-foreground">{key}:</span>
                                <strong className="ml-2">{String(value)}</strong>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>

                      <div>
                        <div className="text-sm text-muted-foreground mb-2">风险评估</div>
                        <div className="p-3 bg-warning/10 rounded border border-warning/30">
                          <p className="text-sm">{autoDecisionDetail.finalDecision.riskAssessment}</p>
                        </div>
                      </div>

                      <div>
                        <div className="text-sm text-muted-foreground mb-2">备选方案</div>
                        <div className="space-y-2">
                          {autoDecisionDetail.finalDecision.alternatives.map((alt, i) => (
                            <div key={i} className="p-3 bg-muted rounded text-sm">
                              {alt}
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}
                </Card>

                {/* 执行结果 */}
                {autoDecisionDetail.executionResult && (
                  <Card className="p-4">
                    <h4 className="mb-3">执行结果</h4>
                    <div className="space-y-4">
                      <div className="flex items-center gap-4 text-sm">
                        <div>
                          <span className="text-muted-foreground">开始时间:</span>
                          <strong className="ml-2">{autoDecisionDetail.executionResult.startTime}</strong>
                        </div>
                        <div>
                          <span className="text-muted-foreground">结束时间:</span>
                          <strong className="ml-2">{autoDecisionDetail.executionResult.endTime}</strong>
                        </div>
                      </div>

                      <div>
                        <div className="text-sm text-muted-foreground mb-2">实际效果</div>
                        <div className="p-3 bg-success/10 rounded space-y-1 text-sm">
                          {Object.entries(autoDecisionDetail.executionResult.actualEffect).map(([key, value]) => (
                            <div key={key}>
                              <span className="text-muted-foreground">{key}:</span>
                              <strong className="ml-2">{String(value)}</strong>
                            </div>
                          ))}
                        </div>
                      </div>

                      <div className="p-4 bg-info/10 rounded border border-info/30">
                        <div className="flex items-center gap-2 mb-2">
                          <Info className="w-5 h-5 text-info" />
                          <strong>偏差分析</strong>
                        </div>
                        <p className="text-sm">{autoDecisionDetail.executionResult.deviation}</p>
                      </div>

                      <div className="p-4 bg-success/10 rounded border border-success/30">
                        <div className="flex items-center gap-2 mb-2">
                          <CheckCircle className="w-5 h-5 text-success" />
                          <strong>效果评价</strong>
                        </div>
                        <p className="text-sm">{autoDecisionDetail.executionResult.evaluation}</p>
                      </div>
                    </div>
                  </Card>
                )}
              </TabsContent>

              {/* 手动添加决策详情 */}
              <TabsContent value="manual" className="space-y-6">
                {/* 基本信息 */}
                <Card className="p-4">
                  <h4 className="mb-3">基本信息</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <div className="text-muted-foreground mb-1">决策编号</div>
                      <div className="font-medium">{manualDecisionDetail.decisionNo}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">决策名称</div>
                      <div className="font-medium">{manualDecisionDetail.title}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">决策类型</div>
                      <div className="font-medium">
                        {getTypeBadge(manualDecisionDetail.type)}
                      </div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">决策级别</div>
                      <div className="font-medium">
                        {getLevelBadge(manualDecisionDetail.level)}
                      </div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">置信度</div>
                      <div className="font-medium">{(manualDecisionDetail.manualInput.confidence * 100).toFixed(0)}%</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">创建人</div>
                      <div className="font-medium">{manualDecisionDetail.createdBy}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-1">创建时间</div>
                      <div className="font-medium">{manualDecisionDetail.createdAt}</div>
                    </div>
                  </div>
                </Card>

                {/* 执行设置 */}
                <Card className="p-4">
                  <h4 className="mb-3">执行设置</h4>
                  <div className="space-y-4">
                    <div>
                      <div className="text-sm text-muted-foreground mb-2">执行模式</div>
                      <div className="flex items-center gap-2">
                        {manualDecisionDetail.manualInput.executionMode === 'manual' ? (
                          <Badge variant="outline" className="bg-info/10 text-info border-info/30">
                            <User className="w-3 h-3 mr-1" />
                            手动执行
                          </Badge>
                        ) : (
                          <Badge variant="outline" className="bg-success/10 text-success border-success/30">
                            <Zap className="w-3 h-3 mr-1" />
                            自动执行
                          </Badge>
                        )}
                      </div>
                    </div>

                    {/* 触发条件（自动执行时） */}
                    {manualDecisionDetail.manualInput.executionMode === 'auto' && manualDecisionDetail.triggerCondition && (
                      <div>
                        <div className="text-sm text-muted-foreground mb-2">触发条件（阈值触发）</div>
                        <div className="p-3 bg-warning/10 rounded border border-warning/30 text-sm">
                          <div className="mb-1">
                            <span className="text-muted-foreground">设备:</span>
                            <strong className="ml-2">{manualDecisionDetail.triggerCondition.device}</strong>
                          </div>
                          <div className="mb-1">
                            <span className="text-muted-foreground">参数:</span>
                            <strong className="ml-2">{manualDecisionDetail.triggerCondition.parameter}</strong>
                          </div>
                          <div>
                            <span className="text-muted-foreground">条件:</span>
                            <strong className="ml-2">
                              {manualDecisionDetail.triggerCondition.operator} {manualDecisionDetail.triggerCondition.value}
                            </strong>
                          </div>
                          <div className="mt-2 pt-2 border-t border-yellow-300 text-xs text-muted-foreground">
                            当条件满足时将自动执行此决策
                          </div>
                        </div>
                      </div>
                    )}

                    {/* 执行目标 */}
                    {manualDecisionDetail.execution && (
                      <div>
                        <div className="text-sm text-muted-foreground mb-2">执行目标</div>
                        <div className="p-3 bg-success/10 rounded border border-success/30 text-sm">
                          <div className="mb-1">
                            <span className="text-muted-foreground">控制设备:</span>
                            <strong className="ml-2">{manualDecisionDetail.execution.device}</strong>
                          </div>
                          <div className="mb-1">
                            <span className="text-muted-foreground">执行动作:</span>
                            <strong className="ml-2">
                              {manualDecisionDetail.execution.action === 'open' ? '打开' : '关闭'}
                            </strong>
                          </div>
                          {manualDecisionDetail.execution.duration && (
                            <div>
                              <span className="text-muted-foreground">持续时长:</span>
                              <strong className="ml-2">{manualDecisionDetail.execution.duration}分钟</strong>
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </Card>

                {/* 决策内容 */}
                <Card className="p-4">
                  <h4 className="mb-3">决策内容</h4>
                  <div className="space-y-4">
                    <div>
                      <div className="text-sm text-muted-foreground mb-2">推荐建议</div>
                      <div className="p-4 bg-info/10 rounded border border-info/30">
                        <p className="text-sm whitespace-pre-line">{manualDecisionDetail.manualInput.recommendation}</p>
                      </div>
                    </div>

                    {manualDecisionDetail.manualInput.explanation && (
                      <div>
                        <div className="text-sm text-muted-foreground mb-2">详细说明</div>
                        <div className="p-4 bg-muted rounded border">
                          <p className="text-sm whitespace-pre-line">{manualDecisionDetail.manualInput.explanation}</p>
                        </div>
                      </div>
                    )}

                    {manualDecisionDetail.manualInput.actionItems && (
                      <div>
                        <div className="text-sm text-muted-foreground mb-2">执行步骤</div>
                        <div className="p-4 bg-success/10 rounded border border-success/30">
                          <ol className="text-sm space-y-1 list-decimal list-inside">
                            {manualDecisionDetail.manualInput.actionItems.split('\n').map((item, idx) => (
                              item.trim() && <li key={idx}>{item.trim()}</li>
                            ))}
                          </ol>
                        </div>
                      </div>
                    )}
                  </div>
                </Card>

                {/* 执行结果 */}
                {manualDecisionDetail.executionResult && (
                  <Card className="p-4">
                    <h4 className="mb-3">执行结果</h4>
                    <div className="space-y-4">
                      <div className="flex items-center gap-4 text-sm">
                        <div>
                          <span className="text-muted-foreground">开始时间:</span>
                          <strong className="ml-2">{manualDecisionDetail.executionResult.startTime}</strong>
                        </div>
                        <div>
                          <span className="text-muted-foreground">结束时间:</span>
                          <strong className="ml-2">{manualDecisionDetail.executionResult.endTime}</strong>
                        </div>
                      </div>

                      <div>
                        <div className="text-sm text-muted-foreground mb-2">实际效果</div>
                        <div className="p-3 bg-success/10 rounded space-y-1 text-sm">
                          {Object.entries(manualDecisionDetail.executionResult.actualEffect).map(([key, value]) => (
                            <div key={key}>
                              <span className="text-muted-foreground">{key}:</span>
                              <strong className="ml-2">{String(value)}</strong>
                            </div>
                          ))}
                        </div>
                      </div>

                      <div className="p-4 bg-success/10 rounded border border-success/30">
                        <div className="flex items-center gap-2 mb-2">
                          <CheckCircle className="w-5 h-5 text-success" />
                          <strong>效果评价</strong>
                        </div>
                        <p className="text-sm">{manualDecisionDetail.executionResult.evaluation}</p>
                      </div>
                    </div>
                  </Card>
                )}
              </TabsContent>
            </Tabs>
          )}

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