import { useState, useEffect } from 'react';
import { AIBusinessFusion } from '../ai/AIBusinessFusion';
import { AIDecisionSimulation } from '../ai/AIDecisionSimulation';
import { AIDecisionLog } from '../ai/AIDecisionLog';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Progress } from '../ui/progress';
import { Switch } from '../ui/switch';
import { Slider } from '../ui/slider';
import {
  Lightbulb,
  Plus,
  Search,
  Download,
  RefreshCw,
  CheckCircle,
  XCircle,
  AlertCircle,
  PlayCircle,
  Settings,
  Eye,
  Edit,
  Trash2,
  FileText,
  Brain,
  Layers,
  GitBranch,
  Code,
  BarChart3,
  Activity,
  Clock,
  Calendar,
  Filter,
  Target,
  Zap,
  TrendingUp,
  Beaker,
  BookOpen,
  Database,
  Cpu,
  CheckCircle2,
  ArrowRight,
  Copy,
  History,
  Info,
  Merge,
  ChevronRight,
  TreeDeciduous,
  Droplet,
  Sprout,
  Upload,
  Bug,
} 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,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface AIDecisionGenerationProps {
  activePath?: string;
}

type RuleType = '阈值规则' | '逻辑规则' | '加权规则' | '专家规则';
type RuleStatus = '启用' | '禁用' | '测试中';
type DecisionLevel = '紧急' | '重要' | '一般' | '建议';
type SimulationStatus = '成功' | '失败' | '警告';

interface BusinessRule {
  id: string;
  name: string;
  type: RuleType;
  category: string;
  description: string;
  condition: string;
  action: string;
  priority: number;
  weight?: number;
  status: RuleStatus;
  createTime: string;
  updateTime: string;
  usageCount: number;
  successRate: number;
}

interface DecisionRecord {
  id: string;
  decisionNo: string;
  applicationName: string;
  decisionType: string;
  decisionLevel: DecisionLevel;
  inputData: {
    source: string;
    fields: Record<string, any>;
  };
  modelOutput: {
    modelName: string;
    modelVersion: string;
    prediction: any;
    confidence: number;
  };
  rulesApplied: {
    ruleId: string;
    ruleName: string;
    matched: boolean;
    output?: string;
  }[];
  contextInfo: {
    fieldId?: string;
    cropType?: string;
    growthStage?: string;
    historicalOperations?: string[];
  };
  finalDecision: string;
  reasoning: string;
  confidence: number;
  timestamp: string;
  executionTime: number;
}

interface SimulationScenario {
  id: string;
  name: string;
  description: string;
  inputData: Record<string, any>;
  expectedOutput?: string;
}

interface SimulationResult {
  scenarioName: string;
  status: SimulationStatus;
  decision: string;
  confidence: number;
  rulesTriggered: number;
  executionTime: number;
  reasoning: string;
}

export function AIDecisionGeneration({ activePath }: AIDecisionGenerationProps) {
  // 如果是业务融合路径，直接返回业务融合组件
  if (activePath && activePath.includes('/decision/fusion')) {
    return <AIBusinessFusion activePath={activePath} />;
  }

  // 如果是决策模拟路径，直接返回决策模拟组件
  if (activePath && activePath.includes('/decision/simulation')) {
    return <AIDecisionSimulation activePath={activePath} />;
  }

  // 如果是决策日志路径，直接返回决策日志组件
  if (activePath && activePath.includes('/decision/log')) {
    return <AIDecisionLog activePath={activePath} />;
  }

  const [activeTab, setActiveTab] = useState('overview');
  const [showRuleDialog, setShowRuleDialog] = useState(false);
  const [showSimulationDialog, setShowSimulationDialog] = useState(false);
  const [selectedRule, setSelectedRule] = useState<BusinessRule | null>(null);
  const [selectedDecision, setSelectedDecision] = useState<DecisionRecord | null>(null);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      // 这里可以根据其他子路径切换Tab
    }
  }, [activePath]);

  // 业务规则数据
  const [businessRules] = useState<BusinessRule[]>([
    {
      id: 'rule-1',
      name: '土壤湿度灌溉决策',
      type: '阈值规则',
      category: '智能灌溉',
      description: '根据土壤湿度阈值决定灌溉量',
      condition: '土壤湿度 < 30% AND 天气预报无降水',
      action: '启动灌溉，灌溉量 = (50% - 当前湿度) × 地块面积 × 0.8',
      priority: 1,
      status: '启用',
      createTime: '2024-08-15',
      updateTime: '2024-10-10',
      usageCount: 856,
      successRate: 98.5,
    },
    {
      id: 'rule-2',
      name: '病虫害预警等级判定',
      type: '加权规则',
      category: '病虫害预警',
      description: '综合置信度、历史病害、环境因素加权判定预警等级',
      condition: '模型置信度 × 0.4 + 历史频率 × 0.3 + 环境适宜度 × 0.3',
      action: '总分 > 0.8:紧急, 0.6-0.8:重要, 0.4-0.6:一般, <0.4:建议',
      priority: 1,
      weight: 0.4,
      status: '启用',
      createTime: '2024-09-01',
      updateTime: '2024-10-12',
      usageCount: 1240,
      successRate: 96.8,
    },
    {
      id: 'rule-3',
      name: '施肥时机判断',
      type: '逻辑规则',
      category: '施肥推荐',
      description: '基于生长阶段和养分水平判断最佳施肥时机',
      condition: '(生长阶段 IN [分蘖期, 拔节期, 抽穗期]) AND (氮含量 < 阈值)',
      action: '推荐施肥，肥料类型和用量根据缺素情况动态计算',
      priority: 2,
      status: '启用',
      createTime: '2024-07-20',
      updateTime: '2024-10-05',
      usageCount: 425,
      successRate: 94.2,
    },
    {
      id: 'rule-4',
      name: '极端天气应对策略',
      type: '专家规则',
      category: '风险预警',
      description: '极端天气条件下的应急决策',
      condition: '(暴雨预警 OR 高温预警 OR 霜冻预警) AND 作物处于关键生长期',
      action: '生成应急方案：提前收获/加固设施/增加灌溉等',
      priority: 1,
      status: '启用',
      createTime: '2024-06-10',
      updateTime: '2024-09-28',
      usageCount: 68,
      successRate: 100,
    },
  ]);

  // 决策记录数据
  const [decisionRecords] = useState<DecisionRecord[]>([
    {
      id: 'dec-1',
      decisionNo: 'DEC-20241015-001',
      applicationName: '智能灌溉策略生成',
      decisionType: '灌溉决策',
      decisionLevel: '重要',
      inputData: {
        source: '土壤传感器 + 气象API',
        fields: {
          土壤湿度: 28.5,
          土壤温度: 18.3,
          气温: 24.5,
          降水概率: 15,
          地块面积: 3.2,
        },
      },
      modelOutput: {
        modelName: '灌溉优化模型',
        modelVersion: 'v2.1.0',
        prediction: { 建议灌溉量: 550, 最佳时段: '06:00-08:00' },
        confidence: 0.92,
      },
      rulesApplied: [
        { ruleId: 'rule-1', ruleName: '土壤湿度灌溉决策', matched: true, output: '灌溉量: 550L' },
      ],
      contextInfo: {
        fieldId: '3号田块',
        cropType: '番茄',
        growthStage: '开花期',
        historicalOperations: ['上次灌溉: 3天前', '本月累计: 2次'],
      },
      finalDecision: '建议于明日06:00-08:00对3号田块进行灌溉，灌溉量550升，重点覆盖南侧区域',
      reasoning: '当前土壤湿度28.5%低于番茄开花期最佳湿度35-45%，未来3天无降水，需及时补充水分。根据地块面积3.2亩和目标湿度，计算灌溉量为550升。考虑蒸发量，建议清晨时段灌溉效果最佳。',
      confidence: 0.92,
      timestamp: '2024-10-15 18:05:32',
      executionTime: 2.3,
    },
    {
      id: 'dec-2',
      decisionNo: 'DEC-20241015-002',
      applicationName: '病虫害智能预警',
      decisionType: '病虫害预警',
      decisionLevel: '紧急',
      inputData: {
        source: '监控摄像头 + 环境传感器',
        fields: {
          图像分析: '叶片黄化病斑',
          温度: 26.8,
          湿度: 72,
          历史病害: '去年同期发生过早疫病',
        },
      },
      modelOutput: {
        modelName: '病虫害识别模型',
        modelVersion: 'v1.8.0',
        prediction: { 病害类型: '番茄早疫病', 感染程度: '中度' },
        confidence: 0.94,
      },
      rulesApplied: [
        { ruleId: 'rule-2', ruleName: '病虫害预警等级判定', matched: true, output: '预警等级: 紧急' },
      ],
      contextInfo: {
        fieldId: '1号大棚',
        cropType: '番茄',
        growthStage: '结果期',
        historicalOperations: ['上次喷药: 15天前'],
      },
      finalDecision: '紧急预警！1号大棚番茄疑似早疫病中度感染，建议立即隔离病株，72小时内使用百菌清喷施防治',
      reasoning: '模型识别置信度94%，结合历史病害记录和当前高温高湿环境（26.8℃，72%湿度）极适合病菌繁殖，加权评分0.86属于紧急级别。需立即采取防控措施避免扩散。',
      confidence: 0.94,
      timestamp: '2024-10-15 14:32:18',
      executionTime: 1.8,
    },
    {
      id: 'dec-3',
      decisionNo: 'DEC-20241014-001',
      applicationName: '精准施肥推荐',
      decisionType: '施肥决策',
      decisionLevel: '一般',
      inputData: {
        source: '土壤检测数据',
        fields: {
          氮含量: 45,
          磷含量: 28,
          钾含量: 62,
          有机质: 2.8,
          pH值: 6.5,
        },
      },
      modelOutput: {
        modelName: '施肥决策模型',
        modelVersion: 'v3.0.1',
        prediction: { 推荐配方: 'N-P-K 15-10-5', 施用量: 25 },
        confidence: 0.89,
      },
      rulesApplied: [
        { ruleId: 'rule-3', ruleName: '施肥时机判断', matched: true, output: '当前适宜施肥' },
      ],
      contextInfo: {
        fieldId: '2号田块',
        cropType: '黄瓜',
        growthStage: '结瓜期',
        historicalOperations: ['上次施肥: 20天前', '目标产量: 8000kg/亩'],
      },
      finalDecision: '建议于3日内对2号田块施用复合肥（N-P-K 15-10-5）25kg/亩，重点补充氮磷元素',
      reasoning: '土壤检测显示氮含量45mg/kg、磷含量28mg/kg低于黄瓜结瓜期最佳水平，钾含量充足。结合目标产量和生长阶段，推荐配方N-P-K 15-10-5，施用量25kg/亩。',
      confidence: 0.89,
      timestamp: '2024-10-14 08:15:42',
      executionTime: 3.5,
    },
  ]);

  // 模拟场景
  const [simulationScenarios] = useState<SimulationScenario[]>([
    {
      id: 'scenario-1',
      name: '干旱情况灌溉决策',
      description: '模拟长期干旱条件下的灌溉策略',
      inputData: {
        土壤湿度: 18.5,
        天气预报: '未来7天无降水',
        作物类型: '番茄',
        生长阶段: '开花期',
        地块面积: 5.0,
      },
      expectedOutput: '启动紧急灌溉，灌溉量约1000升',
    },
    {
      id: 'scenario-2',
      name: '病虫害高风险预警',
      description: '模拟病虫害高发环境的预警决策',
      inputData: {
        温度: 28.5,
        湿度: 85,
        历史病害: '去年同期早疫病爆发',
        作物类型: '番茄',
        图像分析: '叶片出现小斑点',
      },
      expectedOutput: '发出紧急预警，建议立即防治',
    },
    {
      id: 'scenario-3',
      name: '生长期施肥优化',
      description: '模拟关键生长期的施肥决策',
      inputData: {
        氮含量: 35,
        磷含量: 22,
        钾含量: 55,
        作物类型: '黄瓜',
        生长阶段: '结瓜初期',
        目标产量: 9000,
      },
      expectedOutput: '推荐施用高氮复合肥30kg/亩',
    },
  ]);

  // 统计数据
  const totalRules = businessRules.length;
  const activeRules = businessRules.filter(r => r.status === '启用').length;
  const totalDecisions = decisionRecords.length;
  const avgConfidence = decisionRecords.reduce((sum, d) => sum + d.confidence, 0) / totalDecisions;

  // 决策趋势数据
  const decisionTrend = [
    { date: '10-11', 灌溉: 12, 病虫害: 8, 施肥: 5 },
    { date: '10-12', 灌溉: 15, 病虫害: 10, 施肥: 6 },
    { date: '10-13', 灌溉: 11, 病虫害: 12, 施肥: 4 },
    { date: '10-14', 灌溉: 14, 病虫害: 9, 施肥: 7 },
    { date: '10-15', 灌溉: 16, 病虫害: 11, 施肥: 5 },
  ];

  // 规则使用统计
  const ruleUsageStats = businessRules.map(rule => ({
    name: rule.name.substring(0, 8),
    使用次数: rule.usageCount,
    成功率: rule.successRate,
  }));

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

  const getStatusColor = (status: RuleStatus) => {
    switch (status) {
      case '启用': return 'bg-success-muted text-success-muted-foreground';
      case '禁用': return 'bg-muted text-muted-foreground';
      case '测试中': return 'bg-info-muted text-info-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getLevelColor = (level: DecisionLevel) => {
    switch (level) {
      case '紧急': return 'bg-error-muted text-error-muted-foreground';
      case '重要': return 'bg-warning-muted text-warning-muted-foreground';
      case '一般': return 'bg-info-muted text-info-muted-foreground';
      case '建议': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getSimulationStatusColor = (status: SimulationStatus) => {
    switch (status) {
      case '成功': return 'bg-success-muted text-success-muted-foreground';
      case '失败': return 'bg-error-muted text-error-muted-foreground';
      case '警告': return 'bg-warning-muted text-warning-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const handleSaveRule = () => {
    toast.success('业务规则保存成功');
    setShowRuleDialog(false);
  };

  const handleRunSimulation = () => {
    toast.success('模拟测试已启动，正在计算决策结果...');
    setTimeout(() => {
      toast.success('模拟完成！决策结果已生成');
    }, 2000);
  };

  const handleExportDecision = (decisionNo: string) => {
    toast.success(`决策报告 ${decisionNo} 已导出`);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>智能决策生成</h2>
          <p className="text-sm text-muted-foreground mt-1">
            AI与业务深度融合，生成可解释的精准决策
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <BookOpen className="w-4 h-4 mr-2" />
            规则手册
          </Button>
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            导出日志
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">业务规则</p>
              <p className="mt-2 text-3xl text-info">{activeRules}/{totalRules}</p>
              <p className="text-xs text-info mt-1">启用规则</p>
            </div>
            <Layers className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">决策总数</p>
              <p className="mt-2 text-3xl text-success">{totalDecisions}</p>
              <p className="text-xs text-success mt-1">今日生成</p>
            </div>
            <Lightbulb className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">平均置信度</p>
              <p className="mt-2 text-3xl text-accent">{(avgConfidence * 100).toFixed(1)}%</p>
              <p className="text-xs text-accent mt-1">决策可信度</p>
            </div>
            <Target className="w-12 h-12 text-accent opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">执行成功率</p>
              <p className="mt-2 text-3xl text-warning">97.8%</p>
              <p className="text-xs text-warning mt-1">决策有效性</p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="fusion">业务融合</TabsTrigger>
          <TabsTrigger value="simulation">决策模拟</TabsTrigger>
          <TabsTrigger value="log">决策日志</TabsTrigger>
        </TabsList>

        {/* 业务融合 */}
        <TabsContent value="fusion" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-info-muted/50 to-accent-muted/50 border-info/30">
            <div className="flex items-start gap-2">
              <Layers className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
              <div className="text-sm text-info-muted-foreground">
                <p className="mb-2">业务融合功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>数据融合</strong>: 整合模型输出、业务规则、上下文信息</li>
                  <li>• <strong>规则引擎</strong>: 阈值规则、逻辑规则、加权规则、专家规则</li>
                  <li>• <strong>智能加权</strong>: 根据置信度、历史数据动态调整权重</li>
                  <li>• <strong>语义转换</strong>: 将技术数据转化为可执行决策建议</li>
                  <li>• <strong>可解释性</strong>: 生成决策推理过程，提升透明度</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex gap-4">
            <Button className="bg-info hover:bg-info/90" onClick={() => {
              setSelectedRule(null);
              setShowRuleDialog(true);
            }}>
              <Plus className="w-4 h-4 mr-2" />
              新增规则
            </Button>
            <Button variant="outline">
              <Upload className="w-4 h-4 mr-2" />
              导入规则
            </Button>
          </div>

          {/* 决策生成流程 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <GitBranch className="w-5 h-5 text-info" />
              决策生成流程
            </h4>
            <div className="flex items-center justify-between">
              <div className="flex-1 text-center">
                <div className="w-16 h-16 bg-info-muted rounded-full flex items-center justify-center mx-auto mb-2">
                  <Database className="w-8 h-8 text-info" />
                </div>
                <h5 className="mb-1">数据输入</h5>
                <p className="text-xs text-muted-foreground">传感器数据<br/>模型预测结果</p>
              </div>
              <ArrowRight className="w-6 h-6 text-muted-foreground" />
              <div className="flex-1 text-center">
                <div className="w-16 h-16 bg-accent-muted rounded-full flex items-center justify-center mx-auto mb-2">
                  <Brain className="w-8 h-8 text-accent" />
                </div>
                <h5 className="mb-1">规则匹配</h5>
                <p className="text-xs text-muted-foreground">业务规则引擎<br/>条件判断</p>
              </div>
              <ArrowRight className="w-6 h-6 text-muted-foreground" />
              <div className="flex-1 text-center">
                <div className="w-16 h-16 bg-success-muted rounded-full flex items-center justify-center mx-auto mb-2">
                  <Layers className="w-8 h-8 text-success" />
                </div>
                <h5 className="mb-1">上下文融合</h5>
                <p className="text-xs text-muted-foreground">地块属性<br/>历史操作</p>
              </div>
              <ArrowRight className="w-6 h-6 text-muted-foreground" />
              <div className="flex-1 text-center">
                <div className="w-16 h-16 bg-warning-muted rounded-full flex items-center justify-center mx-auto mb-2">
                  <Lightbulb className="w-8 h-8 text-warning" />
                </div>
                <h5 className="mb-1">决策生成</h5>
                <p className="text-xs text-muted-foreground">可执行建议<br/>推理说明</p>
              </div>
            </div>
          </Card>

          {/* 业务规则列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Code className="w-5 h-5 text-info" />
                业务规则库
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>规则名称</TableHead>
                  <TableHead>规则类型</TableHead>
                  <TableHead>应用场景</TableHead>
                  <TableHead>优先级</TableHead>
                  <TableHead>触发条件</TableHead>
                  <TableHead>执行动作</TableHead>
                  <TableHead>使用统计</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {businessRules.map((rule) => (
                  <TableRow key={rule.id}>
                    <TableCell>
                      <div>
                        <div className="font-medium">{rule.name}</div>
                        <div className="text-xs text-muted-foreground">{rule.description}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{rule.type}</Badge>
                    </TableCell>
                    <TableCell className="text-xs">{rule.category}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs ${
                          rule.priority === 1 ? 'bg-error-muted text-error' :
                          rule.priority === 2 ? 'bg-warning-muted text-warning' :
                          'bg-info-muted text-info'
                        }`}>
                          {rule.priority}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <code className="text-xs bg-muted px-2 py-1 rounded">
                        {rule.condition.substring(0, 30)}...
                      </code>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs max-w-xs truncate">
                        {rule.action}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        <div>使用: {rule.usageCount}次</div>
                        <div className="text-success">成功率: {rule.successRate}%</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(rule.status)}>{rule.status}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedRule(rule);
                          setShowRuleDialog(true);
                        }}>
                          <Edit className="w-3 h-3" />
                        </Button>
                        <Button size="sm" variant="outline">
                          <Eye className="w-3 h-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 规则使用统计 */}
          <Card className="p-4">
            <h4 className="mb-4 flex items-center gap-2">
              <BarChart3 className="w-4 h-4 text-success" />
              规则使用统计
            </h4>
            <ResponsiveContainer width="100%" height={250}>
              <BarChart data={ruleUsageStats}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <RechartsTooltip />
                <Legend />
                <Bar yAxisId="left" dataKey="使用次数" fill="#3b82f6" />
                <Line yAxisId="right" dataKey="成功率" stroke="#10b981" strokeWidth={2} />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>

        {/* 决策模拟 */}
        <TabsContent value="simulation" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-success-muted/50 to-primary/10 border-success/30">
            <div className="flex items-start gap-2">
              <Beaker className="w-5 h-5 text-success flex-shrink-0 mt-0.5" />
              <div className="text-sm text-success-muted-foreground">
                <p className="mb-2">决策模拟功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>模拟环境</strong>: 提供安全的决策测试环境</li>
                  <li>• <strong>场景配置</strong>: 手动输入或选择典型数据场景</li>
                  <li>• <strong>规则引擎</strong>: 运行完整的决策规则引擎</li>
                  <li>• <strong>结果预览</strong>: 实时预览决策结果和推理过程</li>
                  <li>• <strong>多方案对比</strong>: 支持多个场景对比分析</li>
                  <li>• <strong>参数优化</strong>: 帮助优化规则参数与逻辑</li>
                </ul>
              </div>
            </div>
          </Card>

          <Button className="bg-success hover:bg-success/90" onClick={() => setShowSimulationDialog(true)}>
            <Beaker className="w-4 h-4 mr-2" />
            新建模拟测试
          </Button>

          {/* 预设场景 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <Layers className="w-5 h-5 text-success" />
              典型场景库
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {simulationScenarios.map((scenario) => (
                <Card key={scenario.id} className="p-4 border-2 hover:border-success transition-all cursor-pointer">
                  <h5 className="mb-2 flex items-center gap-2">
                    {scenario.name.includes('灌溉') && <Droplet className="w-4 h-4 text-info" />}
                    {scenario.name.includes('病虫害') && <Bug className="w-4 h-4 text-destructive" />}
                    {scenario.name.includes('施肥') && <Sprout className="w-4 h-4 text-success" />}
                    {scenario.name}
                  </h5>
                  <p className="text-xs text-muted-foreground mb-3">{scenario.description}</p>
                  <div className="space-y-1 mb-3">
                    {Object.entries(scenario.inputData).slice(0, 3).map(([key, value]) => (
                      <div key={key} className="text-xs flex justify-between">
                        <span className="text-muted-foreground">{key}:</span>
                        <span className="font-medium">{value}</span>
                      </div>
                    ))}
                  </div>
                  <Button size="sm" className="w-full" onClick={handleRunSimulation}>
                    <PlayCircle className="w-3 h-3 mr-1" />
                    运行模拟
                  </Button>
                </Card>
              ))}
            </div>
          </Card>

          {/* 模拟结果示例 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <Activity className="w-5 h-5 text-info" />
              模拟测试结果
            </h4>
            <div className="space-y-4">
              <Card className="p-4 bg-success/10 border-success/30">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <h5 className="flex items-center gap-2">
                      <CheckCircle className="w-4 h-4 text-success" />
                      干旱情况灌溉决策
                    </h5>
                    <p className="text-xs text-muted-foreground mt-1">模拟时间: 2024-10-15 16:30:25</p>
                  </div>
                  <Badge className="bg-success-muted text-success-muted-foreground">成功</Badge>
                </div>
                <div className="space-y-2 mb-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">决策结果:</span>
                    <span className="font-medium">启动紧急灌溉，灌溉量980升</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">置信度:</span>
                    <span className="font-medium text-success">95.2%</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">触发规则:</span>
                    <span className="font-medium">2个规则</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">执行时间:</span>
                    <span className="font-medium">1.8秒</span>
                  </div>
                </div>
                <div className="p-3 bg-white rounded border">
                  <p className="text-xs"><strong>推理过程：</strong></p>
                  <p className="text-xs text-muted-foreground mt-1">
                    土壤湿度18.5%远低于番茄开花期最佳湿度35-45%，且未来7天无降水预报，属于严重干旱。
                    根据地块面积5.0亩和目标湿度计算，灌溉量为980升。触发"土壤湿度灌溉决策"和"极端天气应对策略"两条规则。
                  </p>
                </div>
              </Card>
            </div>
          </Card>
        </TabsContent>

        {/* 决策日志 */}
        <TabsContent value="log" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-accent-muted/50 to-accent-muted border-accent/30">
            <div className="flex items-start gap-2">
              <History className="w-5 h-5 text-accent flex-shrink-0 mt-0.5" />
              <div className="text-sm text-accent-muted-foreground">
                <p className="mb-2">决策日志功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>完整记录</strong>: 记录每一条决策的完整生成过程</li>
                  <li>• <strong>输入追溯</strong>: 保存触发输入数据的详细明细</li>
                  <li>• <strong>模型追踪</strong>: 记录调用的模型服务及版本</li>
                  <li>• <strong>规则日志</strong>: 记录匹配的规则条目和计算结果</li>
                  <li>• <strong>结构化查询</strong>: 支持多维度查询和筛选</li>
                  <li>• <strong>审计追溯</strong>: 为决策透明度和问题排查提供依据</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 搜索和筛选 */}
          <Card className="p-4">
            <div className="flex gap-4">
              <div className="flex-1">
                <Input placeholder="搜索决策编号、应用名称..." prefix={<Search className="w-4 h-4" />} />
              </div>
              <Select defaultValue="all-type">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="决策类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-type">全部类型</SelectItem>
                  <SelectItem value="irrigation">灌溉决策</SelectItem>
                  <SelectItem value="pest">病虫害预警</SelectItem>
                  <SelectItem value="fertilizer">施肥决策</SelectItem>
                </SelectContent>
              </Select>
              <Select defaultValue="all-level">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="决策等级" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-level">全部等级</SelectItem>
                  <SelectItem value="urgent">紧急</SelectItem>
                  <SelectItem value="important">重要</SelectItem>
                  <SelectItem value="normal">一般</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </Card>

          {/* 决策记录列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <FileText className="w-5 h-5 text-accent" />
                决策记录
              </h3>
            </div>
            <div className="divide-y">
              {decisionRecords.map((record) => (
                <div key={record.id} className="p-4 hover:bg-accent transition-colors">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <h4 className="font-medium">{record.applicationName}</h4>
                        <Badge className={getLevelColor(record.decisionLevel)}>{record.decisionLevel}</Badge>
                        <span className="text-xs text-muted-foreground">#{record.decisionNo}</span>
                      </div>
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {record.timestamp}
                        </span>
                        <span className="flex items-center gap-1">
                          <Zap className="w-3 h-3" />
                          {record.executionTime}s
                        </span>
                        <span className="flex items-center gap-1">
                          <Target className="w-3 h-3" />
                          置信度: {(record.confidence * 100).toFixed(1)}%
                        </span>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => setSelectedDecision(record)}>
                        <Eye className="w-3 h-3" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleExportDecision(record.decisionNo)}>
                        <Download className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div className="p-3 bg-info/10 rounded">
                      <p className="text-xs text-muted-foreground mb-1">输入数据</p>
                      <div className="space-y-0.5">
                        <p className="text-xs"><strong>数据源:</strong> {record.inputData.source}</p>
                        {Object.entries(record.inputData.fields).slice(0, 2).map(([key, value]) => (
                          <p key={key} className="text-xs">{key}: {value}</p>
                        ))}
                      </div>
                    </div>

                    <div className="p-3 bg-accent/20 rounded">
                      <p className="text-xs text-muted-foreground mb-1">模型输出</p>
                      <div className="space-y-0.5">
                        <p className="text-xs"><strong>模型:</strong> {record.modelOutput.modelName}</p>
                        <p className="text-xs"><strong>版本:</strong> {record.modelOutput.modelVersion}</p>
                        <p className="text-xs"><strong>置信度:</strong> {(record.modelOutput.confidence * 100).toFixed(1)}%</p>
                      </div>
                    </div>
                  </div>

                  <div className="p-3 bg-success/10 rounded mb-3">
                    <p className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
                      <Lightbulb className="w-3 h-3" />
                      最终决策
                    </p>
                    <p className="text-sm">{record.finalDecision}</p>
                  </div>

                  <div className="p-3 bg-muted rounded">
                    <p className="text-xs text-muted-foreground mb-1">推理过程</p>
                    <p className="text-xs">{record.reasoning}</p>
                    <div className="flex gap-2 mt-2">
                      {record.rulesApplied.map((rule, idx) => (
                        <Badge key={idx} variant="outline" className="text-xs">
                          {rule.ruleName}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* 决策趋势 */}
          <Card className="p-4">
            <h4 className="mb-4 flex items-center gap-2">
              <TrendingUp className="w-4 h-4 text-accent" />
              决策生成趋势
            </h4>
            <ResponsiveContainer width="100%" height={250}>
              <BarChart data={decisionTrend}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <RechartsTooltip />
                <Legend />
                <Bar dataKey="灌溉" stackId="a" fill="#3b82f6" />
                <Bar dataKey="病虫害" stackId="a" fill="#f59e0b" />
                <Bar dataKey="施肥" stackId="a" fill="#10b981" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 规则编辑对话框 */}
      <Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{selectedRule ? '编辑规则' : '新增规则'}</DialogTitle>
            <DialogDescription>
              配置业务规则的条件、动作和优先级
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>规则名称</Label>
                <Input placeholder="输入规则名称" defaultValue={selectedRule?.name} />
              </div>
              <div>
                <Label>规则类型</Label>
                <Select defaultValue={selectedRule?.type}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择规则类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="阈值规则">阈值规则</SelectItem>
                    <SelectItem value="逻辑规则">逻辑规则</SelectItem>
                    <SelectItem value="加权规则">加权规则</SelectItem>
                    <SelectItem value="专家规则">专家规则</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>应用场景</Label>
                <Select defaultValue={selectedRule?.category}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择应用场景" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="智能灌溉">智能灌溉</SelectItem>
                    <SelectItem value="病虫害预警">病虫害预警</SelectItem>
                    <SelectItem value="施肥推荐">施肥推荐</SelectItem>
                    <SelectItem value="风险预警">风险预警</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>优先级</Label>
                <Select defaultValue={selectedRule?.priority.toString()}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择优先级" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1">高优先级 (1)</SelectItem>
                    <SelectItem value="2">中优先级 (2)</SelectItem>
                    <SelectItem value="3">低优先级 (3)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>规则描述</Label>
              <Textarea placeholder="描述规则的功能和适用场景..." rows={2} defaultValue={selectedRule?.description} />
            </div>

            <div>
              <Label>触发条件</Label>
              <Textarea 
                placeholder="输入触发条件表达式，如：土壤湿度 < 30% AND 天气预报无降水" 
                rows={2} 
                defaultValue={selectedRule?.condition}
                className="font-mono text-sm"
              />
            </div>

            <div>
              <Label>执行动作</Label>
              <Textarea 
                placeholder="输入执行动作逻辑，如：启动灌溉，灌溉量 = (50% - 当前湿度) × 地块面积 × 0.8" 
                rows={3} 
                defaultValue={selectedRule?.action}
                className="font-mono text-sm"
              />
            </div>

            <div className="flex items-center justify-between p-4 bg-info/10 rounded-lg">
              <div>
                <div className="font-medium">启用规则</div>
                <div className="text-xs text-muted-foreground">规则创建后立即生效</div>
              </div>
              <Switch defaultChecked={selectedRule?.status === '启用'} />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRuleDialog(false)}>
              取消
            </Button>
            <Button className="bg-info hover:bg-info/90" onClick={handleSaveRule}>
              保存规则
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 模拟测试对话框 */}
      <Dialog open={showSimulationDialog} onOpenChange={setShowSimulationDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>决策模拟测试</DialogTitle>
            <DialogDescription>
              配置模拟场景参数，测试决策结果
            </DialogDescription>
          </DialogHeader>

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

            <div>
              <Label>应用类型</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="选择应用类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="irrigation">智能灌溉</SelectItem>
                  <SelectItem value="pest">病虫害预警</SelectItem>
                  <SelectItem value="fertilizer">施肥推荐</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-3">
              <Label>输入参数配置</Label>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs">土壤湿度 (%)</Label>
                  <Input type="number" placeholder="0-100" />
                </div>
                <div>
                  <Label className="text-xs">温度 (℃)</Label>
                  <Input type="number" placeholder="0-50" />
                </div>
                <div>
                  <Label className="text-xs">湿度 (%)</Label>
                  <Input type="number" placeholder="0-100" />
                </div>
                <div>
                  <Label className="text-xs">地块面积 (亩)</Label>
                  <Input type="number" placeholder="0-100" />
                </div>
              </div>
            </div>

            <div>
              <Label>作物类型</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="选择作物" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="tomato">番茄</SelectItem>
                  <SelectItem value="cucumber">黄瓜</SelectItem>
                  <SelectItem value="pepper">辣椒</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>生长阶段</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="选择生长阶段" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="seedling">苗期</SelectItem>
                  <SelectItem value="flowering">开花期</SelectItem>
                  <SelectItem value="fruiting">结果期</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowSimulationDialog(false)}>
              取消
            </Button>
            <Button className="bg-success hover:bg-success/90" onClick={handleRunSimulation}>
              <PlayCircle className="w-4 h-4 mr-2" />
              运行模拟
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 决策详情对话框 */}
      <Dialog open={selectedDecision !== null} onOpenChange={() => setSelectedDecision(null)}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>决策详情</DialogTitle>
            <DialogDescription>
              决策编号: {selectedDecision?.decisionNo}
            </DialogDescription>
          </DialogHeader>

          {selectedDecision && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>应用名称</Label>
                  <div className="field-value">{selectedDecision.applicationName}</div>
                </div>
                <div>
                  <Label>决策类型</Label>
                  <div className="field-value">{selectedDecision.decisionType}</div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>决策等级</Label>
                  <div className="field-value">
                    <Badge className={getLevelColor(selectedDecision.decisionLevel)}>
                      {selectedDecision.decisionLevel}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label>生成时间</Label>
                  <div className="field-value">{selectedDecision.timestamp}</div>
                </div>
              </div>

              <div>
                <Label>输入数据</Label>
                <div className="field-value">
                  <div className="space-y-1">
                    <p className="text-sm"><strong>数据源:</strong> {selectedDecision.inputData.source}</p>
                    {Object.entries(selectedDecision.inputData.fields).map(([key, value]) => (
                      <p key={key} className="text-sm">{key}: {value}</p>
                    ))}
                  </div>
                </div>
              </div>

              <div>
                <Label>模型输出</Label>
                <div className="field-value">
                  <div className="space-y-1">
                    <p className="text-sm"><strong>模型:</strong> {selectedDecision.modelOutput.modelName} {selectedDecision.modelOutput.modelVersion}</p>
                    <p className="text-sm"><strong>预测结果:</strong> {JSON.stringify(selectedDecision.modelOutput.prediction)}</p>
                    <p className="text-sm"><strong>置信度:</strong> {(selectedDecision.modelOutput.confidence * 100).toFixed(1)}%</p>
                  </div>
                </div>
              </div>

              <div>
                <Label>匹配规则</Label>
                <div className="field-value">
                  <div className="space-y-2">
                    {selectedDecision.rulesApplied.map((rule, idx) => (
                      <div key={idx} className="p-2 bg-info/10 rounded">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-sm font-medium">{rule.ruleName}</span>
                          {rule.matched ? (
                            <CheckCircle className="w-4 h-4 text-success" />
                          ) : (
                            <XCircle className="w-4 h-4 text-muted-foreground" />
                          )}
                        </div>
                        {rule.output && <p className="text-xs">{rule.output}</p>}
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              <div>
                <Label>上下文信息</Label>
                <div className="field-value">
                  <div className="space-y-1">
                    {selectedDecision.contextInfo.fieldId && (
                      <p className="text-sm">地块: {selectedDecision.contextInfo.fieldId}</p>
                    )}
                    {selectedDecision.contextInfo.cropType && (
                      <p className="text-sm">作物: {selectedDecision.contextInfo.cropType}</p>
                    )}
                    {selectedDecision.contextInfo.growthStage && (
                      <p className="text-sm">生长阶段: {selectedDecision.contextInfo.growthStage}</p>
                    )}
                    {selectedDecision.contextInfo.historicalOperations?.map((op, idx) => (
                      <p key={idx} className="text-sm text-muted-foreground">{op}</p>
                    ))}
                  </div>
                </div>
              </div>

              <div>
                <Label>最终决策</Label>
                <div className="field-value bg-success/10">
                  {selectedDecision.finalDecision}
                </div>
              </div>

              <div>
                <Label>推理过程</Label>
                <div className="field-value">
                  {selectedDecision.reasoning}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>置信度</Label>
                  <div className="field-value">
                    <div className="flex items-center gap-2">
                      <Progress value={selectedDecision.confidence * 100} className="flex-1" />
                      <span className="text-sm font-medium">{(selectedDecision.confidence * 100).toFixed(1)}%</span>
                    </div>
                  </div>
                </div>
                <div>
                  <Label>执行时间</Label>
                  <div className="field-value">{selectedDecision.executionTime}秒</div>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setSelectedDecision(null)}>
              关闭
            </Button>
            <Button onClick={() => handleExportDecision(selectedDecision?.decisionNo || '')}>
              <Download className="w-4 h-4 mr-2" />
              导出报告
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
