import { useState, useEffect } from 'react';
import { AIKnowledgeGeneration } from '../ai/AIKnowledgeGeneration';
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 {
  BookOpen,
  Search,
  Download,
  RefreshCw,
  Filter,
  Star,
  TrendingUp,
  Lightbulb,
  Eye,
  ThumbsUp,
  MessageSquare,
  Sparkles,
  Brain,
  Database,
  FileText,
  Clock,
  Tag,
  CheckCircle,
  AlertCircle,
  Info,
  Zap,
  Target,
  BarChart3,
  Activity,
  Copy,
  Share2,
  Bookmark,
  BookmarkCheck,
  Award,
  Layers,
  GitBranch,
  Code,
  List,
  Grid,
  Send,
  Bot,
  User,
  ChevronRight,
  Plus,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';

interface AIKnowledgeBaseProps {
  activePath?: string;
}

export function AIKnowledgeBase({ activePath }: AIKnowledgeBaseProps) {
  // 如果是AI知识自动生成路径，直接返回AI知识自动生成组件
  if (activePath && activePath.includes('/knowledge/generation')) {
    return <AIKnowledgeGeneration activePath={activePath} />;
  }

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

function AIKnowledgeBaseContent({ activePath }: AIKnowledgeBaseProps) {

type KnowledgeType = '模型知识' | '规则知识' | '案例知识' | '经验知识';
type KnowledgeStatus = '已验证' | '待验证' | '已废弃';
type CaseType = '成功案例' | '失败案例' | '典型案例';

interface Knowledge {
  id: string;
  knowledgeNo: string;
  title: string;
  type: KnowledgeType;
  category: string;
  content: string;
  source: string;
  modelName?: string;
  applicableScenarios: string[];
  effectivenessConditions: string[];
  keyPoints: string[];
  relatedDecisions: number;
  successRate: number;
  status: KnowledgeStatus;
  createTime: string;
  updateTime: string;
  usageCount: number;
  rating: number;
}

interface Case {
  id: string;
  caseNo: string;
  title: string;
  type: CaseType;
  category: string;
  description: string;
  background: {
    fieldInfo: string;
    cropType: string;
    season: string;
    problem: string;
  };
  solution: {
    decision: string;
    modelUsed: string;
    rulesApplied: string[];
    parameters: Record<string, any>;
  };
  result: {
    outcome: string;
    metrics: Record<string, any>;
    feedback: string;
  };
  keyLearnings: string[];
  tags: string[];
  createTime: string;
  viewCount: number;
  likeCount: number;
  bookmarked: boolean;
}

interface QARecord {
  id: string;
  question: string;
  answer: string;
  category: string;
  relatedKnowledge: string[];
  confidence: number;
  helpful: boolean | null;
  createTime: string;
}

  const [activeView, setActiveView] = useState<'knowledge' | 'cases' | 'qa'>('knowledge');
  const [viewMode, setViewMode] = useState<'list' | 'grid'>('list');
  const [showKnowledgeDetail, setShowKnowledgeDetail] = useState(false);
  const [showCaseDetail, setShowCaseDetail] = useState(false);
  const [selectedKnowledge, setSelectedKnowledge] = useState<Knowledge | null>(null);
  const [selectedCase, setSelectedCase] = useState<Case | null>(null);
  const [qaQuestion, setQAQuestion] = useState('');
  const [qaHistory, setQAHistory] = useState<QARecord[]>([]);
  const [showVerifyDialog, setShowVerifyDialog] = useState(false);
  const [verifyingKnowledge, setVerifyingKnowledge] = useState<Knowledge | null>(null);

  // 知识数据
  const [knowledgeBase, setKnowledgeBase] = useState<Knowledge[]>([
    {
      id: 'kb-1',
      knowledgeNo: 'KB-2024-001',
      title: '番茄早疫病识别模型适用场景',
      type: '模型知识',
      category: '病虫害识别',
      content: '番茄早疫病识别模型(v1.8.0)在温室大棚环境下表现最佳，特别适用于叶片特写图像分析。模型对病斑特征（黄化、同心轮纹）识别准确率达94%以上。',
      source: '模型训练数据分析',
      modelName: '病虫害识别模型 v1.8.0',
      applicableScenarios: [
        '温室大棚番茄种植',
        '生长期中后期（开花期至结果期）',
        '高温高湿环境（温度25-30℃，湿度>70%）',
      ],
      effectivenessConditions: [
        '图像清晰度 > 1080p',
        '光照充足（>10000 lux）',
        '拍摄距离 20-50cm',
        '病斑明显可见',
      ],
      keyPoints: [
        '早期黄化斑点是关键识别特征',
        '同心轮纹是确诊的重要依据',
        '需结合环境数据（温湿度）提升准确性',
      ],
      relatedDecisions: 156,
      successRate: 94.2,
      status: '已验证',
      createTime: '2024-09-15',
      updateTime: '2024-10-10',
      usageCount: 156,
      rating: 4.8,
    },
    {
      id: 'kb-2',
      knowledgeNo: 'KB-2024-002',
      title: '土壤湿度阈值灌溉规则有效性分析',
      type: '规则知识',
      category: '灌溉控制',
      content: '基于856次灌溉决策的数据分析，当土壤湿度<30%且未来3天无降水时，灌溉决策成功率达99.2%。灌溉量计算公式：(目标湿度-当前湿度) × 地块面积 × 0.8 系数。',
      source: '决策执行数据统计',
      applicableScenarios: [
        '露天田块灌溉',
        '沙壤土质地块',
        '春夏季节（蒸发量大）',
      ],
      effectivenessConditions: [
        '土壤湿度传感器精度 ±2%',
        '天气预报准确率 >85%',
        '地块排水良好',
      ],
      keyPoints: [
        '30%是关键阈值，低于此值作物易受旱',
        '0.8系数考虑了土壤保水性和蒸发损失',
        '需提前6-12小时执行，避开高温时段',
      ],
      relatedDecisions: 856,
      successRate: 99.2,
      status: '已验证',
      createTime: '2024-08-20',
      updateTime: '2024-10-12',
      usageCount: 856,
      rating: 4.9,
    },
    {
      id: 'kb-3',
      knowledgeNo: 'KB-2024-003',
      title: '黄瓜结瓜期施肥决策最佳实践',
      type: '经验知识',
      category: '施肥管理',
      content: '黄瓜结瓜期需肥量大，氮磷钾需求比例约为2:1:2。根据425次成功施肥案例总结，当氮含量<45mg/kg、磷含量<25mg/kg时，施用N-P-K 15-10-5复合肥25-30kg/亩效果最佳。',
      source: '农艺专家经验 + 历史数据分析',
      applicableScenarios: [
        '黄瓜结瓜初期至盛瓜期',
        '大棚或露天栽培',
        '目标产量 8000-10000kg/亩',
      ],
      effectivenessConditions: [
        '土壤检测数据准确',
        '作物长势正常',
        'pH值 6.0-7.0',
      ],
      keyPoints: [
        '分次施用效果优于一次性施肥',
        '配合有机肥使用提升效果',
        '施肥后及时浇水促进养分吸收',
      ],
      relatedDecisions: 425,
      successRate: 96.8,
      status: '已验证',
      createTime: '2024-07-10',
      updateTime: '2024-10-08',
      usageCount: 425,
      rating: 4.7,
    },
    {
      id: 'kb-4',
      knowledgeNo: 'KB-2024-004',
      title: '小麦赤霉病AI预测模型准确性验证',
      type: '模型知识',
      category: '病虫害预测',
      content: '新开发的小麦赤霉病AI预测模型（v1.0.0）基于气象数据和历史病害数据，可提前7-10天预测赤霉病发生概率。初步测试显示预测准确率达87%，但仍需在更多地区和年份进行验证。',
      source: 'AI模型自动生成',
      modelName: '小麦病害预测模型 v1.0.0',
      applicableScenarios: [
        '小麦扬花期至灌浆期',
        '降雨频繁地区（年降水量>600mm）',
        '温度适中（15-20℃）',
      ],
      effectivenessConditions: [
        '气象数据准确性>90%',
        '历史病害数据完整',
        '地块环境与训练数据相似',
      ],
      keyPoints: [
        '扬花期遇连续阴雨是关键风险因素',
        '温度15-20℃且湿度>80%时风险最高',
        '预测提前期为7-10天，便于提前防治',
      ],
      relatedDecisions: 23,
      successRate: 87.0,
      status: '待验证',
      createTime: '2024-10-18',
      updateTime: '2024-10-20',
      usageCount: 23,
      rating: 4.2,
    },
    {
      id: 'kb-5',
      knowledgeNo: 'KB-2024-005',
      title: '智能施肥决策优化算法应用规则',
      type: '规则知识',
      category: '施肥管理',
      content: '基于机器学习的智能施肥决策算法（v2.0）通过分析土壤养分、作物生长阶段、气候条件等多维数据，自动计算最优施肥方案。算法推荐的氮磷钾配比与传统农艺师建议略有差异，需要进一步验证其长期效果。',
      source: 'AI算法自动生成',
      applicableScenarios: [
        '精准农业管理地块',
        '配备土壤传感器的智能大棚',
        '追求高产量和高品质的经济作物',
      ],
      effectivenessConditions: [
        '土壤传感器实时监测',
        '气象数据接入完整',
        '作物生长模型参数准确',
      ],
      keyPoints: [
        '算法考虑了土壤缓冲性和养分释放速率',
        '施肥时机建议比传统方法提前1-2天',
        '推荐分次施肥，单次用量减少20-30%',
      ],
      relatedDecisions: 15,
      successRate: 82.5,
      status: '待验证',
      createTime: '2024-10-21',
      updateTime: '2024-10-22',
      usageCount: 15,
      rating: 4.0,
    },
  ]);

  // 案例库数据
  const [caseLibrary] = useState<Case[]>([
    {
      id: 'case-1',
      caseNo: 'CASE-2024-001',
      title: '1号大棚番茄早疫病成功防治案例',
      type: '成功案例',
      category: '病虫害防治',
      description: '通过AI病虫害识别模型及时发现早疫病，72小时内完成防治，有效控制病害扩散',
      background: {
        fieldInfo: '1号大棚，2.5亩',
        cropType: '番茄',
        season: '2024年秋季',
        problem: '叶片出现黄化斑点，疑似病害',
      },
      solution: {
        decision: '紧急预警！建议立即隔离病株，72小时内使用百菌清喷施',
        modelUsed: '病虫害识别模型 v1.8.0',
        rulesApplied: ['病虫害预警等级判定', '高温高湿病害风险'],
        parameters: {
          置信度: 0.94,
          病害类型: '番茄早疫病',
          感染程度: '中度',
          环境温度: 26.8,
          环境湿度: 72,
        },
      },
      result: {
        outcome: '防治成功，病害得到有效控制',
        metrics: {
          处理时效: '48小时',
          病株隔离: '15株',
          喷药次数: 2,
          病害控制率: '95%',
          产量损失: '<5%',
        },
        feedback: '及时发现和处理避免了病害大面积扩散，保护了大部分作物',
      },
      keyLearnings: [
        'AI图像识别能够早期发现病害，比人工巡查提前2-3天',
        '高温高湿环境需加强监测频率',
        '隔离病株是控制扩散的关键措施',
        '72小时黄金处理期不可错过',
      ],
      tags: ['病虫害', '番茄', '早疫病', '成功案例', 'AI识别'],
      createTime: '2024-10-16',
      viewCount: 156,
      likeCount: 42,
      bookmarked: true,
    },
    {
      id: 'case-2',
      caseNo: 'CASE-2024-002',
      title: '3号田块智能灌溉优化案例',
      type: '典型案例',
      category: '灌溉管理',
      description: '基于AI灌溉决策模型，实现精准灌溉，节水30%的同时保证作物正常生长',
      background: {
        fieldInfo: '3号田块，5.0亩',
        cropType: '番茄',
        season: '2024年夏季',
        problem: '传统灌溉方式用水量大，水资源浪费严重',
      },
      solution: {
        decision: '基于土壤湿度和天气预报的智能灌溉策略',
        modelUsed: '灌溉优化模型 v2.1.0',
        rulesApplied: ['土壤湿度阈值灌溉规则'],
        parameters: {
          土壤湿度阈值: '30%',
          目标湿度: '45%',
          灌溉时段: '06:00-08:00',
          流量控制: '自动调节',
        },
      },
      result: {
        outcome: '节水效果显著，作物生长良好',
        metrics: {
          节水率: '30%',
          灌溉次数: '从每周5次降至3次',
          水资源节约: '约2000L/周',
          产量: '与传统方式持平',
          作物品质: '优',
        },
        feedback: '智能灌溉系统运行稳定，大大降低了人工成本和水资源消耗',
      },
      keyLearnings: [
        '精准灌溉可以大幅节约水资源',
        '清晨灌溉蒸发损失最小',
        'AI模型能够预测未来需水量',
        '自动化控制提升管理效率',
      ],
      tags: ['灌溉', '节水', '智能控制', '番茄', '典型案例'],
      createTime: '2024-10-10',
      viewCount: 203,
      likeCount: 68,
      bookmarked: false,
    },
  ]);

  // 问答记录
  const [qaRecords] = useState<QARecord[]>([
    {
      id: 'qa-1',
      question: '番茄叶片出现黄色斑点是什么病害？',
      answer: '根据知识库分析，番茄叶片黄色斑点可能是早疫病的早期症状。早疫病的典型特征包括：1) 叶片出现黄化斑点；2) 病斑逐渐扩大形成同心轮纹；3) 高温高湿环境下易发病。建议使用病虫害识别模型进行确诊，置信度可达94%以上。如确诊，应立即隔离病株并在72小时内使用百菌清等杀菌剂防治。',
      category: '病虫害诊断',
      relatedKnowledge: ['KB-2024-001', 'CASE-2024-001'],
      confidence: 0.94,
      helpful: true,
      createTime: '2024-10-15 14:30:00',
    },
    {
      id: 'qa-2',
      question: '土壤湿度多少时需要灌溉？',
      answer: '根据灌溉控制知识库，当土壤湿度低于30%且未来3天无降水预报时，建议启动灌溉。最佳灌溉策略是将土壤湿度提升至45-50%（番茄等果菜类作物）。建议在清晨6:00-8:00进行灌溉，此时蒸发量小，水分利用率高。灌溉量可根据公式计算：(目标湿度-当前湿度) × 地块面积 × 0.8。',
      category: '灌溉管理',
      relatedKnowledge: ['KB-2024-002', 'CASE-2024-002'],
      confidence: 0.99,
      helpful: true,
      createTime: '2024-10-14 09:15:00',
    },
    {
      id: 'qa-3',
      question: '黄瓜结瓜期应该如何施肥？',
      answer: '黄瓜结瓜期是需肥高峰期，建议采用以下施肥策略：1) 根据土壤检测，当氮含量<45mg/kg、磷含量<25mg/kg时施肥；2) 使用N-P-K 15-10-5复合肥25-30kg/亩；3) 分2-3次施用效果优于一次性施肥；4) 配合有机肥使用；5) 施肥后及时浇水促进养分吸收。该策略基于425次成功案例，成功率达96.8%。',
      category: '施肥管理',
      relatedKnowledge: ['KB-2024-003'],
      confidence: 0.97,
      helpful: null,
      createTime: '2024-10-13 16:45:00',
    },
  ]);

  // 统计数据
  const totalKnowledge = knowledgeBase.length;
  const totalCases = caseLibrary.length;
  const totalQA = qaRecords.length;
  const avgRating = knowledgeBase.reduce((sum, k) => sum + k.rating, 0) / totalKnowledge;

  // 知识类型分布
  const knowledgeTypeDistribution = [
    { name: '模型知识', value: 12, color: '#3b82f6' },
    { name: '规则知识', value: 18, color: '#10b981' },
    { name: '案例知识', value: 25, color: '#f59e0b' },
    { name: '经验知识', value: 15, color: '#8b5cf6' },
  ];

  // 知识使用趋势
  const knowledgeUsageTrend = [
    { month: '6月', 模型: 45, 规则: 68, 案例: 32 },
    { month: '7月', 模型: 52, 规则: 75, 案例: 41 },
    { month: '8月', 模型: 68, 规则: 92, 案例: 56 },
    { month: '9月', 模型: 78, 规则: 105, 案例: 68 },
    { month: '10月', 模型: 85, 规则: 118, 案例: 75 },
  ];

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

  const handleAskQuestion = () => {
    if (!qaQuestion.trim()) {
      toast.error('请输入问题');
      return;
    }

    // 模拟AI回答
    toast.success('AI正在分析您的问题...');
    
    setTimeout(() => {
      const newQA: QARecord = {
        id: `qa-${Date.now()}`,
        question: qaQuestion,
        answer: '根据知识库分析，正在为您生成答案...',
        category: '智能问答',
        relatedKnowledge: [],
        confidence: 0.85,
        helpful: null,
        createTime: new Date().toLocaleString('zh-CN'),
      };
      
      setQAHistory([newQA, ...qaHistory]);
      setQAQuestion('');
      toast.success('AI已生成答案');
    }, 1500);
  };

  const handleMarkHelpful = (qaId: string, helpful: boolean) => {
    toast.success(helpful ? '感谢您的反馈！' : '我们会继续优化');
  };

  const handleBookmarkCase = (caseId: string) => {
    toast.success('案例已收藏');
  };

  const handleVerifyKnowledge = (knowledge: Knowledge) => {
    setVerifyingKnowledge(knowledge);
    setShowVerifyDialog(true);
  };

  const confirmVerifyKnowledge = () => {
    if (!verifyingKnowledge) return;

    // 更新知识状态为已验证
    setKnowledgeBase(knowledgeBase.map(k => 
      k.id === verifyingKnowledge.id 
        ? { ...k, status: '已验证' as KnowledgeStatus, updateTime: new Date().toISOString().split('T')[0] }
        : k
    ));

    toast.success(`知识"${verifyingKnowledge.title}"已验证通过`);
    setShowVerifyDialog(false);
    setVerifyingKnowledge(null);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>AI知识库</h2>
          <p className="text-sm text-muted-foreground mt-1">
            智能沉淀，知识赋能，持续优化
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            更新知识库
          </Button>
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            导出知识
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">知识总量</p>
              <p className="mt-2 text-3xl text-info">{totalKnowledge}</p>
              <p className="text-xs text-info mt-1">条知识条目</p>
            </div>
            <Database 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">{totalCases}</p>
              <p className="text-xs text-success mt-1">个典型案例</p>
            </div>
            <FileText className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">问答记录</p>
              <p className="mt-2 text-3xl text-accent-foreground">{totalQA}</p>
              <p className="text-xs text-accent-foreground mt-1">次智能问答</p>
            </div>
            <MessageSquare className="w-12 h-12 text-accent-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">平均评分</p>
              <p className="mt-2 text-3xl text-warning">{avgRating.toFixed(1)}</p>
              <p className="text-xs text-warning mt-1">知识质量</p>
            </div>
            <Star className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeView} onValueChange={(v) => setActiveView(v as any)}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="knowledge">知识库</TabsTrigger>
          <TabsTrigger value="cases">案例库</TabsTrigger>
          <TabsTrigger value="qa">智能问答</TabsTrigger>
        </TabsList>

        {/* 知识库 */}
        <TabsContent value="knowledge" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-info-muted to-accent border-info">
            <div className="flex items-start gap-2">
              <Sparkles 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">AI知识自动生成与应用：</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>: AI驱动的知识问答系统</li>
                  <li>• <strong>持续优化</strong>: 知识库自我学习和优化能力</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 筛选和搜索 */}
          <Card className="p-4">
            <div className="flex items-center justify-between mb-4">
              <div className="flex gap-4 flex-1">
                <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="model">模型知识</SelectItem>
                    <SelectItem value="rule">规则知识</SelectItem>
                    <SelectItem value="case">案例知识</SelectItem>
                    <SelectItem value="experience">经验知识</SelectItem>
                  </SelectContent>
                </Select>
                <Select defaultValue="all-category">
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="知识分类" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all-category">全部分类</SelectItem>
                    <SelectItem value="pest">病虫害识别</SelectItem>
                    <SelectItem value="irrigation">灌溉控制</SelectItem>
                    <SelectItem value="fertilizer">施肥管理</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex gap-2 ml-4">
                <Button
                  size="sm"
                  variant={viewMode === 'list' ? 'default' : 'outline'}
                  onClick={() => setViewMode('list')}
                >
                  <List className="w-4 h-4" />
                </Button>
                <Button
                  size="sm"
                  variant={viewMode === 'grid' ? 'default' : 'outline'}
                  onClick={() => setViewMode('grid')}
                >
                  <Grid className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </Card>

          {/* 知识列表 */}
          {viewMode === 'list' ? (
            <Card>
              <div className="p-4 border-b">
                <h3 className="flex items-center gap-2">
                  <BookOpen className="w-5 h-5 text-info" />
                  知识条目
                </h3>
              </div>
              <div className="divide-y">
                {knowledgeBase.map((knowledge) => (
                  <div key={knowledge.id} className="p-4 hover:bg-muted/50 transition-colors">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h4>{knowledge.title}</h4>
                          <Badge variant="outline">{knowledge.type}</Badge>
                          <Badge 
                            className={
                              knowledge.status === '已验证' ? 'bg-success-muted text-success-muted-foreground' :
                              knowledge.status === '待验证' ? 'bg-warning-muted text-warning-muted-foreground' :
                              'bg-muted text-muted-foreground'
                            }
                          >
                            {knowledge.status}
                          </Badge>
                          <span className="text-xs text-muted-foreground">#{knowledge.knowledgeNo}</span>
                        </div>
                        <p className="text-sm text-muted-foreground mb-2">{knowledge.content}</p>
                      </div>
                    </div>

                    <div className="grid grid-cols-3 gap-4 mb-3">
                      <Card className="p-3 bg-info-muted">
                        <p className="text-xs text-muted-foreground mb-2">适用场景</p>
                        <div className="space-y-1">
                          {knowledge.applicableScenarios.slice(0, 2).map((scenario, idx) => (
                            <p key={idx} className="text-xs flex items-start gap-1">
                              <CheckCircle className="w-3 h-3 text-info flex-shrink-0 mt-0.5" />
                              {scenario}
                            </p>
                          ))}
                        </div>
                      </Card>

                      <Card className="p-3 bg-success-muted">
                        <p className="text-xs text-muted-foreground mb-2">有效性条件</p>
                        <div className="space-y-1">
                          {knowledge.effectivenessConditions.slice(0, 2).map((condition, idx) => (
                            <p key={idx} className="text-xs flex items-start gap-1">
                              <Target className="w-3 h-3 text-success flex-shrink-0 mt-0.5" />
                              {condition}
                            </p>
                          ))}
                        </div>
                      </Card>

                      <Card className="p-3 bg-warning-muted">
                        <p className="text-xs text-muted-foreground mb-2">关键要点</p>
                        <div className="space-y-1">
                          {knowledge.keyPoints.slice(0, 2).map((point, idx) => (
                            <p key={idx} className="text-xs flex items-start gap-1">
                              <Lightbulb className="w-3 h-3 text-warning flex-shrink-0 mt-0.5" />
                              {point}
                            </p>
                          ))}
                        </div>
                      </Card>
                    </div>

                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Activity className="w-3 h-3" />
                          使用 {knowledge.usageCount} 次
                        </span>
                        <span className="flex items-center gap-1">
                          <Target className="w-3 h-3" />
                          成功率 {knowledge.successRate}%
                        </span>
                        <span className="flex items-center gap-1">
                          <Star className="w-3 h-3 fill-warning text-warning" />
                          {knowledge.rating}
                        </span>
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          更新于 {knowledge.updateTime}
                        </span>
                      </div>
                      <div className="flex gap-2">
                        {knowledge.status === '待验证' && (
                          <Button 
                            size="sm" 
                            variant="default"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleVerifyKnowledge(knowledge);
                            }}
                          >
                            <CheckCircle className="w-3 h-3 mr-1" />
                            验证
                          </Button>
                        )}
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedKnowledge(knowledge);
                          setShowKnowledgeDetail(true);
                        }}>
                          <Eye className="w-3 h-3 mr-1" />
                          查看详情
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </Card>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {knowledgeBase.map((knowledge) => (
                <Card key={knowledge.id} className="p-4 hover:shadow-lg transition-shadow cursor-pointer" onClick={() => {
                  setSelectedKnowledge(knowledge);
                  setShowKnowledgeDetail(true);
                }}>
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <Badge variant="outline">{knowledge.type}</Badge>
                      <Badge 
                        className={
                          knowledge.status === '已验证' ? 'bg-success-muted text-success-muted-foreground' :
                          knowledge.status === '待验证' ? 'bg-warning-muted text-warning-muted-foreground' :
                          'bg-muted text-muted-foreground'
                        }
                      >
                        {knowledge.status}
                      </Badge>
                    </div>
                    <div className="flex items-center gap-1">
                      <Star className="w-4 h-4 fill-warning text-warning" />
                      <span className="text-sm">{knowledge.rating}</span>
                    </div>
                  </div>
                  <h4 className="mb-2">{knowledge.title}</h4>
                  <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                    {knowledge.content}
                  </p>
                  <div className="flex items-center justify-between text-xs text-muted-foreground mb-3">
                    <span>使用 {knowledge.usageCount} 次</span>
                    <span>成功率 {knowledge.successRate}%</span>
                  </div>
                  {knowledge.status === '待验证' && (
                    <Button 
                      size="sm" 
                      className="w-full"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleVerifyKnowledge(knowledge);
                      }}
                    >
                      <CheckCircle className="w-4 h-4 mr-1" />
                      验证知识
                    </Button>
                  )}
                </Card>
              ))}
            </div>
          )}

          {/* 知识统计 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-info" />
                知识类型分布
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <PieChart>
                  <Pie
                    data={knowledgeTypeDistribution}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {knowledgeTypeDistribution.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <RechartsTooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-success" />
                知识使用趋势
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={knowledgeUsageTrend}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Line type="monotone" dataKey="模型" stroke="#3b82f6" strokeWidth={2} />
                  <Line type="monotone" dataKey="规则" stroke="#10b981" strokeWidth={2} />
                  <Line type="monotone" dataKey="案例" stroke="#f59e0b" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 案例库 */}
        <TabsContent value="cases" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-success-muted to-accent border-success">
            <div className="flex items-start gap-2">
              <Award 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>
                </ul>
              </div>
            </div>
          </Card>

          {/* 案例列表 */}
          <div className="grid grid-cols-1 gap-4">
            {caseLibrary.map((caseItem) => (
              <Card key={caseItem.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <h3>{caseItem.title}</h3>
                      <Badge className={
                        caseItem.type === '成功案例' ? 'bg-success-muted text-success-muted-foreground' :
                        caseItem.type === '失败案例' ? 'bg-error-muted text-error-muted-foreground' :
                        'bg-info-muted text-info-muted-foreground'
                      }>
                        {caseItem.type}
                      </Badge>
                      <Badge variant="outline">{caseItem.category}</Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">{caseItem.description}</p>
                  </div>
                  <Button
                    size="sm"
                    variant={caseItem.bookmarked ? 'default' : 'outline'}
                    onClick={() => handleBookmarkCase(caseItem.id)}
                  >
                    {caseItem.bookmarked ? (
                      <BookmarkCheck className="w-4 h-4" />
                    ) : (
                      <Bookmark className="w-4 h-4" />
                    )}
                  </Button>
                </div>

                <div className="grid grid-cols-3 gap-4 mb-4">
                  <Card className="p-4 bg-info-muted">
                    <h5 className="mb-2 flex items-center gap-2">
                      <Info className="w-4 h-4 text-info" />
                      背景信息
                    </h5>
                    <div className="space-y-1 text-xs">
                      <p><strong>地块:</strong> {caseItem.background.fieldInfo}</p>
                      <p><strong>作物:</strong> {caseItem.background.cropType}</p>
                      <p><strong>季节:</strong> {caseItem.background.season}</p>
                      <p><strong>问题:</strong> {caseItem.background.problem}</p>
                    </div>
                  </Card>

                  <Card className="p-4 bg-accent-muted">
                    <h5 className="mb-2 flex items-center gap-2">
                      <Brain className="w-4 h-4 text-accent" />
                      解决方案
                    </h5>
                    <div className="space-y-1 text-xs">
                      <p><strong>决策:</strong> {caseItem.solution.decision.substring(0, 30)}...</p>
                      <p><strong>模型:</strong> {caseItem.solution.modelUsed}</p>
                      <p><strong>规则:</strong> {caseItem.solution.rulesApplied.length}条</p>
                    </div>
                  </Card>

                  <Card className="p-4 bg-success-muted">
                    <h5 className="mb-2 flex items-center gap-2">
                      <CheckCircle className="w-4 h-4 text-success" />
                      执行结果
                    </h5>
                    <div className="space-y-1 text-xs">
                      <p><strong>结果:</strong> {caseItem.result.outcome}</p>
                      {Object.entries(caseItem.result.metrics).slice(0, 2).map(([key, value]) => (
                        <p key={key}><strong>{key}:</strong> {value}</p>
                      ))}
                    </div>
                  </Card>
                </div>

                <div className="mb-4">
                  <h5 className="mb-2 flex items-center gap-2">
                    <Lightbulb className="w-4 h-4 text-warning" />
                    关键学习点
                  </h5>
                  <ul className="space-y-1">
                    {caseItem.keyLearnings.map((learning, idx) => (
                      <li key={idx} className="text-sm flex items-start gap-2">
                        <ChevronRight className="w-4 h-4 text-warning flex-shrink-0 mt-0.5" />
                        {learning}
                      </li>
                    ))}
                  </ul>
                </div>

                <div className="flex items-center justify-between">
                  <div className="flex gap-2">
                    {caseItem.tags.map((tag, idx) => (
                      <Badge key={idx} variant="outline" className="text-xs">
                        <Tag className="w-3 h-3 mr-1" />
                        {tag}
                      </Badge>
                    ))}
                  </div>
                  <div className="flex items-center gap-4 text-xs text-muted-foreground">
                    <span className="flex items-center gap-1">
                      <Eye className="w-3 h-3" />
                      {caseItem.viewCount}
                    </span>
                    <span className="flex items-center gap-1">
                      <ThumbsUp className="w-3 h-3" />
                      {caseItem.likeCount}
                    </span>
                    <Button size="sm" variant="outline" onClick={() => {
                      setSelectedCase(caseItem);
                      setShowCaseDetail(true);
                    }}>
                      查看完整案例
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 智能问答 */}
        <TabsContent value="qa" 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">
              <Bot 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>AI驱动</strong>: 基于知识库的智能问答</li>
                  <li>• <strong>知识关联</strong>: 自动关联相关知识和案例</li>
                  <li>• <strong>置信度评估</strong>: 提供答案可信度评分</li>
                  <li>• <strong>反馈优化</strong>: 根据用户反馈持续改进</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 问答输入 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <MessageSquare className="w-5 h-5 text-accent" />
              向AI提问
            </h3>
            <div className="flex gap-4">
              <Textarea
                placeholder="请输入您的问题，例如：番茄叶片出现黄色斑点是什么病害？"
                value={qaQuestion}
                onChange={(e) => setQAQuestion(e.target.value)}
                rows={3}
                className="flex-1"
              />
              <Button className="bg-accent hover:bg-accent/90" onClick={handleAskQuestion}>
                <Send className="w-4 h-4 mr-2" />
                提问
              </Button>
            </div>
          </Card>

          {/* 问答历史 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <History className="w-5 h-5 text-info" />
              问答记录
            </h3>
            <div className="space-y-6">
              {qaRecords.map((qa) => (
                <div key={qa.id} className="border-l-4 border-accent pl-4">
                  <div className="flex items-start gap-3 mb-3">
                    <div className="w-8 h-8 bg-info-muted rounded-full flex items-center justify-center flex-shrink-0">
                      <User className="w-4 h-4 text-info" />
                    </div>
                    <div className="flex-1">
                      <p className="font-medium mb-1">{qa.question}</p>
                      <p className="text-xs text-muted-foreground">{qa.createTime}</p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3 mb-3">
                    <div className="w-8 h-8 bg-accent-muted rounded-full flex items-center justify-center flex-shrink-0">
                      <Bot className="w-4 h-4 text-accent" />
                    </div>
                    <div className="flex-1">
                      <div className="bg-accent-muted p-4 rounded-lg mb-2">
                        <p className="text-sm leading-relaxed">{qa.answer}</p>
                      </div>
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <Badge variant="outline">{qa.category}</Badge>
                        <span className="flex items-center gap-1">
                          <Target className="w-3 h-3" />
                          置信度: {(qa.confidence * 100).toFixed(0)}%
                        </span>
                        {qa.relatedKnowledge.length > 0 && (
                          <span className="flex items-center gap-1">
                            <BookOpen className="w-3 h-3" />
                            关联知识: {qa.relatedKnowledge.length}条
                          </span>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2 ml-11">
                    <p className="text-xs text-muted-foreground">这个回答有帮助吗？</p>
                    <Button
                      size="sm"
                      variant={qa.helpful === true ? 'default' : 'outline'}
                      onClick={() => handleMarkHelpful(qa.id, true)}
                    >
                      <ThumbsUp className="w-3 h-3" />
                    </Button>
                    <Button
                      size="sm"
                      variant={qa.helpful === false ? 'default' : 'outline'}
                      onClick={() => handleMarkHelpful(qa.id, false)}
                    >
                      <ThumbsUp className="w-3 h-3 rotate-180" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 知识详情对话框 */}
      <Dialog open={showKnowledgeDetail} onOpenChange={setShowKnowledgeDetail}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>知识详情</DialogTitle>
            <DialogDescription>
              知识编号: {selectedKnowledge?.knowledgeNo}
            </DialogDescription>
          </DialogHeader>

          {selectedKnowledge && (
            <div className="space-y-4">
              <div>
                <Label>知识标题</Label>
                <div className="field-value">{selectedKnowledge.title}</div>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label>知识类型</Label>
                  <div className="field-value">
                    <Badge variant="outline">{selectedKnowledge.type}</Badge>
                  </div>
                </div>
                <div>
                  <Label>知识分类</Label>
                  <div className="field-value">{selectedKnowledge.category}</div>
                </div>
                <div>
                  <Label>验证状态</Label>
                  <div className="field-value">
                    <Badge 
                      className={
                        selectedKnowledge.status === '已验证' ? 'bg-success-muted text-success-muted-foreground' :
                        selectedKnowledge.status === '待验证' ? 'bg-warning-muted text-warning-muted-foreground' :
                        'bg-muted text-muted-foreground'
                      }
                    >
                      {selectedKnowledge.status}
                    </Badge>
                  </div>
                </div>
              </div>

              <div>
                <Label>知识内容</Label>
                <div className="field-value">{selectedKnowledge.content}</div>
              </div>

              {selectedKnowledge.modelName && (
                <div>
                  <Label>关联模型</Label>
                  <div className="field-value">{selectedKnowledge.modelName}</div>
                </div>
              )}

              <div>
                <Label>适用场景</Label>
                <div className="field-value">
                  <ul className="space-y-2">
                    {selectedKnowledge.applicableScenarios.map((scenario, idx) => (
                      <li key={idx} className="flex items-start gap-2">
                        <CheckCircle className="w-4 h-4 text-success flex-shrink-0 mt-0.5" />
                        {scenario}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>

              <div>
                <Label>有效性条件</Label>
                <div className="field-value">
                  <ul className="space-y-2">
                    {selectedKnowledge.effectivenessConditions.map((condition, idx) => (
                      <li key={idx} className="flex items-start gap-2">
                        <Target className="w-4 h-4 text-info flex-shrink-0 mt-0.5" />
                        {condition}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>

              <div>
                <Label>关键要点</Label>
                <div className="field-value">
                  <ul className="space-y-2">
                    {selectedKnowledge.keyPoints.map((point, idx) => (
                      <li key={idx} className="flex items-start gap-2">
                        <Lightbulb className="w-4 h-4 text-warning flex-shrink-0 mt-0.5" />
                        {point}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label>使用次数</Label>
                  <div className="field-value">{selectedKnowledge.usageCount}次</div>
                </div>
                <div>
                  <Label>成功率</Label>
                  <div className="field-value text-success">{selectedKnowledge.successRate}%</div>
                </div>
                <div>
                  <Label>知识评分</Label>
                  <div className="field-value flex items-center gap-1">
                    <Star className="w-4 h-4 fill-warning text-warning" />
                    {selectedKnowledge.rating}
                  </div>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowKnowledgeDetail(false)}>
              关闭
            </Button>
            {selectedKnowledge?.status === '待验证' && (
              <Button 
                className="bg-success hover:bg-success/90"
                onClick={() => {
                  setShowKnowledgeDetail(false);
                  handleVerifyKnowledge(selectedKnowledge);
                }}
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                验证知识
              </Button>
            )}
            <Button>
              <Copy className="w-4 h-4 mr-2" />
              复制知识
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 知识验证确认对话框 */}
      <Dialog open={showVerifyDialog} onOpenChange={setShowVerifyDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle className="w-5 h-5 text-success" />
              验证知识
            </DialogTitle>
            <DialogDescription>
              确认验证此知识条目吗？
            </DialogDescription>
          </DialogHeader>

          {verifyingKnowledge && (
            <div className="space-y-4">
              <div className="p-4 bg-info-muted border border-info/30 rounded-lg">
                <div className="mb-2">
                  <span className="text-xs text-muted-foreground">知识编号：</span>
                  <span className="text-sm font-medium">{verifyingKnowledge.knowledgeNo}</span>
                </div>
                <h4 className="mb-2">{verifyingKnowledge.title}</h4>
                <div className="flex items-center gap-2 mb-2">
                  <Badge variant="outline">{verifyingKnowledge.type}</Badge>
                  <Badge variant="outline">{verifyingKnowledge.category}</Badge>
                </div>
                <p className="text-sm text-muted-foreground line-clamp-2">
                  {verifyingKnowledge.content}
                </p>
              </div>

              <div className="p-3 bg-warning-muted border border-warning/30 rounded-lg">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-warning flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-warning-muted-foreground">
                    <p className="font-medium mb-1">验证说明</p>
                    <ul className="space-y-1 text-xs">
                      <li>• 验证后该知识将标记为"已验证"状态</li>
                      <li>• 已验证的知识可以正常应用于决策系统</li>
                      <li>• 待验证知识建议在实际应用中谨慎使用</li>
                      <li>• 验证操作不可撤销，请确认知识内容准确无误</li>
                    </ul>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4 p-3 bg-muted rounded-lg">
                <div>
                  <p className="text-xs text-muted-foreground mb-1">当前状态</p>
                  <Badge className="bg-warning-muted text-warning-muted-foreground">
                    {verifyingKnowledge.status}
                  </Badge>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground mb-1">验证后状态</p>
                  <Badge className="bg-success-muted text-success-muted-foreground">
                    已验证
                  </Badge>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground mb-1">使用次数</p>
                  <p className="text-sm">{verifyingKnowledge.usageCount} 次</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground mb-1">成功率</p>
                  <p className="text-sm text-success">{verifyingKnowledge.successRate}%</p>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowVerifyDialog(false)}>
              取消
            </Button>
            <Button 
              className="bg-success hover:bg-success/90"
              onClick={confirmVerifyKnowledge}
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              确认验证
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 案例详情对话框 */}
      <Dialog open={showCaseDetail} onOpenChange={setShowCaseDetail}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>案例详情</DialogTitle>
            <DialogDescription>
              案例编号: {selectedCase?.caseNo}
            </DialogDescription>
          </DialogHeader>

          {selectedCase && (
            <div className="space-y-4">
              <div>
                <Label>案例标题</Label>
                <div className="field-value">{selectedCase.title}</div>
              </div>

              <div>
                <Label>案例描述</Label>
                <div className="field-value">{selectedCase.description}</div>
              </div>

              <div>
                <Label>背景信息</Label>
                <div className="field-value">
                  <div className="grid grid-cols-2 gap-4">
                    {Object.entries(selectedCase.background).map(([key, value]) => (
                      <div key={key}>
                        <p className="text-xs text-muted-foreground mb-1">{key}</p>
                        <p className="text-sm">{value}</p>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              <div>
                <Label>解决方案</Label>
                <div className="field-value">
                  <div className="space-y-3">
                    <div>
                      <p className="text-xs text-muted-foreground mb-1">决策内容</p>
                      <p className="text-sm">{selectedCase.solution.decision}</p>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <p className="text-xs text-muted-foreground mb-1">使用模型</p>
                        <p className="text-sm">{selectedCase.solution.modelUsed}</p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground mb-1">应用规则</p>
                        <p className="text-sm">{selectedCase.solution.rulesApplied.join(', ')}</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <Label>执行结果</Label>
                <div className="field-value">
                  <div className="space-y-3">
                    <div>
                      <p className="text-xs text-muted-foreground mb-1">结果</p>
                      <p className="text-sm text-success">{selectedCase.result.outcome}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground mb-2">关键指标</p>
                      <div className="grid grid-cols-2 gap-2">
                        {Object.entries(selectedCase.result.metrics).map(([key, value]) => (
                          <p key={key} className="text-sm">
                            <strong>{key}:</strong> {value}
                          </p>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <Label>关键学习点</Label>
                <div className="field-value">
                  <ul className="space-y-2">
                    {selectedCase.keyLearnings.map((learning, idx) => (
                      <li key={idx} className="flex items-start gap-2">
                        <Lightbulb className="w-4 h-4 text-warning flex-shrink-0 mt-0.5" />
                        {learning}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCaseDetail(false)}>
              关闭
            </Button>
            <Button>
              <Share2 className="w-4 h-4 mr-2" />
              分享案例
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
