import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Progress } from '../ui/progress';
import { copyToClipboard } from '../../lib/clipboard';
import { safeNow, formatDateTime } from '../../lib/safeDate';
import {
  Brain,
  BookOpen,
  Lightbulb,
  Search,
  TrendingUp,
  CheckCircle,
  AlertCircle,
  Clock,
  Filter,
  RefreshCw,
  Eye,
  ThumbsUp,
  ThumbsDown,
  Star,
  MessageSquare,
  Send,
  Sparkles,
  Database,
  Target,
  Zap,
  FileText,
  Settings,
  Activity,
  Users,
  Calendar,
  Tag,
  Bookmark,
  Share2,
  Copy,
  Award,
  TrendingDown,
  ArrowRight,
  Plus,
  Edit,
  Trash2,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface AIKnowledgeGenerationProps {
  activePath?: string;
}

// 知识类型
type KnowledgeType = 'scenario' | 'rule' | 'case' | 'pattern' | 'insight';

// 知识状态
type KnowledgeStatus = 'draft' | 'reviewing' | 'published' | 'archived';

// 知识条目
interface KnowledgeItem {
  id: string;
  knowledgeNo: string;
  title: string;
  type: KnowledgeType;
  category: string;
  content: string;
  tags: string[];
  
  // 来源信息
  sourceType: 'auto' | 'manual';
  sourceDecisionId?: string;
  sourceModelId?: string;
  extractedAt?: string;
  
  // 质量指标
  confidence: number;
  accuracy: number;
  useCount: number;
  successRate: number;
  
  // 适用条件
  conditions?: {
    [key: string]: any;
  };
  
  // 效果数据
  impact?: {
    avgImprovement: number;
    casesApplied: number;
    userRating: number;
  };
  
  // 状态
  status: KnowledgeStatus;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
}

// 案例推荐
interface CaseRecommendation {
  id: string;
  caseId: string;
  caseTitle: string;
  similarity: number;
  matchedFeatures: string[];
  decisionType: string;
  outcome: string;
  applicableReason: string;
}

// 智能问答
interface QASession {
  id: string;
  question: string;
  answer: string;
  confidence: number;
  sources: string[];
  relatedCases: string[];
  timestamp: string;
  helpful: boolean | null;
}

export function AIKnowledgeGeneration({ activePath }: AIKnowledgeGenerationProps) {
  const [selectedKnowledge, setSelectedKnowledge] = useState<KnowledgeItem | null>(null);
  const [showKnowledgeDetail, setShowKnowledgeDetail] = useState(false);
  const [showQADialog, setShowQADialog] = useState(false);
  const [currentQuestion, setCurrentQuestion] = useState('');
  const [qaHistory, setQAHistory] = useState<QASession[]>([]);
  
  // 筛选条件
  const [filters, setFilters] = useState({
    type: 'all',
    category: 'all',
    status: 'all',
    searchText: '',
  });

  // 知识库数据
  const [knowledgeItems] = useState<KnowledgeItem[]>([
    {
      id: 'know_001',
      knowledgeNo: 'KNOW-2024-001',
      title: '番茄开花期灌溉最佳时机识别模式',
      type: 'pattern',
      category: '灌溉决策',
      content: `基于120+次成功决策案例分析，提炼出番茄开花期灌溉的最佳时机识别模式：

**核心特征：**
1. 土壤湿度 < 40%
2. 距上次灌溉 > 2天
3. 未来3天无降雨
4. 气温 > 25℃

**最佳时间窗口：**
- 傍晚17:00-18:00（蒸发损失最小）
- 清晨6:00-7:00（次选方案）

**灌溉量计算：**
灌溉量 = (目标湿度 - 当前湿度) × 地块面积 × 系数
- 目标湿度：60-70%
- 系数：0.8-1.0（根据土壤类型调整）

**预期效果：**
- 提高坐果率：15-20%
- 减少水分损失：30%
- 降低病害风险：25%

**适用条件：**
- 作物：番茄
- 生长期：开花期
- 种植方式：大棚种植
- 灌溉方式：滴灌、喷灌`,
      tags: ['番茄', '开花期', '灌溉', '最佳时机', '高成功率'],
      sourceType: 'auto',
      sourceDecisionId: 'dec_001',
      sourceModelId: 'model_001',
      extractedAt: '2024-10-23 18:00:00',
      confidence: 0.95,
      accuracy: 0.92,
      useCount: 45,
      successRate: 0.91,
      conditions: {
        cropType: '番茄',
        growthStage: '开花期',
        plantingMethod: '大棚',
        irrigationType: ['滴灌', '喷灌'],
      },
      impact: {
        avgImprovement: 18.5,
        casesApplied: 45,
        userRating: 4.7,
      },
      status: 'published',
      createdAt: '2024-10-15',
      updatedAt: '2024-10-23',
      createdBy: 'AI自动生成',
    },
    {
      id: 'know_002',
      knowledgeNo: 'KNOW-2024-002',
      title: '黄瓜病虫害预警规则有效性分析',
      type: 'rule',
      category: '病虫害防治',
      content: `通过对80+次病虫害预警决策的分析，总结出黄瓜病虫害预警规则的有效性条件：

**高效规则（准确率>85%）：**

1. **霜霉病预警规则**
   - 条件：湿度>85% AND 温度18-24℃ AND 持续时间>6小时
   - 准确率：91%
   - 误报率：7%
   - 漏报率：9%

2. **白粉病预警规则**
   - 条件：湿度60-80% AND 温度20-28℃ AND 通风不良
   - 准确率：87%
   - 误报率：10%
   - 漏报率：13%

3. **蚜虫预警规则**
   - 条件：温度>25℃ AND 湿度<60% AND 叶片嫩绿
   - 准确率：89%
   - 误报率：8%
   - 漏报率：11%

**失效场景分析：**
- 规则1在温度>28℃时准确率下降至65%
- 规则2在湿度>90%时易产生误报
- 规则3在阴雨天失效

**优化建议：**
1. 增加温度上限条件
2. 引入降雨量参数
3. 结合历史发病数据调整阈值`,
      tags: ['黄瓜', '病虫害', '预警规则', '准确率', '优化'],
      sourceType: 'auto',
      extractedAt: '2024-10-20 10:00:00',
      confidence: 0.88,
      accuracy: 0.89,
      useCount: 32,
      successRate: 0.86,
      conditions: {
        cropType: '黄瓜',
        decisionType: '病虫害预警',
      },
      impact: {
        avgImprovement: 23.5,
        casesApplied: 32,
        userRating: 4.5,
      },
      status: 'published',
      createdAt: '2024-10-18',
      updatedAt: '2024-10-20',
      createdBy: 'AI自动生成',
    },
    {
      id: 'know_003',
      knowledgeNo: 'KNOW-2024-003',
      title: '需水预测模型适用场景总结',
      type: 'scenario',
      category: '模型应用',
      content: `基于模型实际使用数据，总结作物需水预测模型的最佳适用场景：

**高准确度场景（误差<5%）：**

1. **场景A：露地蔬菜种植**
   - 作物类型：叶菜类（生菜、菠菜）
   - 生长阶段：苗期、生长期
   - 天气条件：晴天为主
   - 模型准确率：95%
   - 建议置信度阈值：>0.9

2. **场景B：大棚果蔬**
   - 作物类型：番茄、黄瓜、茄子
   - 生长阶段：开花期、结果期
   - 环境控制：可控温湿度
   - 模型准确率：92%
   - 建议置信度阈值：>0.85

3. **场景C：水稻种植**
   - 生长阶段：分蘖期、抽穗期
   - 灌溉方式：淹灌
   - 土壤类型：水稻土
   - 模型准确率：90%
   - 建议置信度阈值：>0.85

**低准确度场景（误差>15%）：**
- 极端天气（暴雨、干旱）
- 病虫害高发期
- 新种植品种
- 土壤改良期

**模型参数调优建议：**
- 场景A：增加叶面积指数权重
- 场景B：强化环境参数影响
- 场景C：引入水层深度参数`,
      tags: ['需水预测', '模型应用', '适用场景', '准确率'],
      sourceType: 'auto',
      sourceModelId: 'model_001',
      extractedAt: '2024-10-22 14:30:00',
      confidence: 0.93,
      accuracy: 0.92,
      useCount: 28,
      successRate: 0.90,
      conditions: {
        modelType: '需水预测',
        dataQuality: 'high',
      },
      impact: {
        avgImprovement: 12.3,
        casesApplied: 28,
        userRating: 4.6,
      },
      status: 'published',
      createdAt: '2024-10-20',
      updatedAt: '2024-10-22',
      createdBy: 'AI自动生成',
    },
    {
      id: 'know_004',
      knowledgeNo: 'KNOW-2024-004',
      title: '施肥决策成功案例：玉米追肥最佳方案',
      type: 'case',
      category: '施肥决策',
      content: `【案例背景】
- 地块：5号田（20亩）
- 作物：玉米
- 生长期：拔节期
- 问题：叶色偏黄，长势偏弱

【决策过程】
1. 数据采集：
   - 土壤养分检测：N 45mg/kg（偏低）
   - 叶片SPAD值：38（正常35-45）
   - 生长高度：85cm（正常80-100cm）

2. 模型分析：
   - 养分预测模型：氮素缺乏20%
   - 生长模拟模型：建议追肥尿素15kg/亩

3. 规则匹配：
   - 拔节期追肥规则：氮肥为主
   - 用量计算：(目标养分-当前养分)×系数
   - 结果：尿素12kg/亩 + 钾肥5kg/亩

【执行方案】
- 施肥时间：拔节初期（6月15日）
- 施肥方式：沟施+浇水
- 施肥量：尿素12kg/亩 + 钾肥5kg/亩
- 总成本：1200元

【实施结果】
- 7天后叶色恢复正常
- 15天后植株高度增加18cm
- 最终产量：650kg/亩（提升15%）
- 经济效益：增收3000元

【经验总结】
1. 拔节期是追肥关键期
2. 氮钾配施效果更佳
3. 沟施+浇水利用率高
4. 成本收益比：1:3.5

【适用条件】
- 作物：玉米、高粱等禾本科
- 生长期：拔节期、大喇叭口期
- 土壤类型：砂壤土、壤土
- 灌溉条件：充足`,
      tags: ['玉米', '施肥', '追肥', '成功案例', '拔节期'],
      sourceType: 'auto',
      sourceDecisionId: 'dec_010',
      extractedAt: '2024-10-21 16:00:00',
      confidence: 0.90,
      accuracy: 0.88,
      useCount: 18,
      successRate: 0.94,
      conditions: {
        cropType: ['玉米', '高粱'],
        growthStage: ['拔节期', '大喇叭口期'],
        soilType: ['砂壤土', '壤土'],
      },
      impact: {
        avgImprovement: 15.2,
        casesApplied: 18,
        userRating: 4.8,
      },
      status: 'published',
      createdAt: '2024-10-19',
      updatedAt: '2024-10-21',
      createdBy: 'AI自动生成',
    },
    {
      id: 'know_005',
      knowledgeNo: 'KNOW-2024-005',
      title: '多模型融合决策的关键洞察',
      type: 'insight',
      category: '决策优化',
      content: `通过对100+次多模型融合决策的深度分析，发现以下关键洞察：

**洞察1：模型权重动态调整提升准确率**
- 固定权重平均准确率：78%
- 动态权重平均准确率：86%
- 提升幅度：10.3%

动态权重策略：
\`\`\`
if 模型置信度 > 0.9:
    权重 = 0.7
elif 模型置信度 > 0.8:
    权重 = 0.5
else:
    权重 = 0.3
\`\`\`

**洞察2：规则与模型互补性分析**
- 纯模型决策成功率：82%
- 纯规则决策成功率：75%
- 融合决策成功率：91%

最佳融合比例：
- 模型输出权重：60%
- 规则建议权重：40%

**洞察3：置信度阈值的影响**
- 阈值0.7：决策量100%，成功率78%
- 阈值0.8：决策量85%，成功率86%
- 阈值0.9：决策量60%，成功率94%

**洞察4：决策时效性分析**
- 即时决策（<10分钟）：成功率83%
- 短期决策（1-3小时）：成功率89%
- 中期决策（3-24小时）：成功率92%

**优化建议：**
1. 根据模型置信度动态调整权重
2. 保持60:40的模型规则融合比
3. 置信度阈值设为0.85
4. 优先采用短期决策窗口`,
      tags: ['多模型融合', '权重优化', '准确率提升', '决策洞察'],
      sourceType: 'auto',
      extractedAt: '2024-10-23 12:00:00',
      confidence: 0.91,
      accuracy: 0.89,
      useCount: 12,
      successRate: 0.92,
      impact: {
        avgImprovement: 10.3,
        casesApplied: 12,
        userRating: 4.9,
      },
      status: 'published',
      createdAt: '2024-10-22',
      updatedAt: '2024-10-23',
      createdBy: 'AI自动生成',
    },
  ]);

  // 案例推荐数据
  const [recommendations] = useState<CaseRecommendation[]>([
    {
      id: 'rec_001',
      caseId: 'know_004',
      caseTitle: '施肥决策成功案例：玉米追肥最佳方案',
      similarity: 0.92,
      matchedFeatures: ['作物类型', '生长阶段', '土壤养分状况', '问题类型'],
      decisionType: '施肥决策',
      outcome: '产量提升15%，收益增加3000元',
      applicableReason: '当前玉米地块处于拔节期，土壤氮素偏低，与该案例高度相似',
    },
    {
      id: 'rec_002',
      caseId: 'know_001',
      caseTitle: '番茄开花期灌溉最佳时机识别模式',
      similarity: 0.88,
      matchedFeatures: ['作物类型', '生长阶段', '土壤湿度', '天气条件'],
      decisionType: '灌溉决策',
      outcome: '坐果率提升18%，水分利用效率提高30%',
      applicableReason: '当前番茄处于开花期，土壤湿度35%，与模式完全匹配',
    },
    {
      id: 'rec_003',
      caseId: 'know_002',
      caseTitle: '黄瓜病虫害预警规则有效性分析',
      similarity: 0.85,
      matchedFeatures: ['作物类型', '环境条件', '病害风险'],
      decisionType: '病虫害预警',
      outcome: '准确率89%，提前3-5天预警',
      applicableReason: '当前黄瓜大棚湿度高，温度适宜，符合霜霉病预警条件',
    },
  ]);

  // 统计数据
  const stats = {
    totalKnowledge: knowledgeItems.length,
    autoGenerated: knowledgeItems.filter(k => k.sourceType === 'auto').length,
    published: knowledgeItems.filter(k => k.status === 'published').length,
    avgConfidence: (knowledgeItems.reduce((sum, k) => sum + k.confidence, 0) / knowledgeItems.length * 100).toFixed(0),
    totalUseCount: knowledgeItems.reduce((sum, k) => sum + k.useCount, 0),
    avgSuccessRate: (knowledgeItems.reduce((sum, k) => sum + k.successRate, 0) / knowledgeItems.length * 100).toFixed(0),
  };

  const getKnowledgeTypeName = (type: KnowledgeType) => {
    const names = {
      scenario: '应用场景',
      rule: '规则分析',
      case: '成功案例',
      pattern: '识别模式',
      insight: '关键洞察',
    };
    return names[type];
  };

  const getKnowledgeTypeIcon = (type: KnowledgeType) => {
    const icons = {
      scenario: Target,
      rule: Settings,
      case: Award,
      pattern: Sparkles,
      insight: Lightbulb,
    };
    return icons[type];
  };

  const getStatusBadge = (status: KnowledgeStatus) => {
    const config = {
      draft: { label: '草稿', className: 'bg-muted text-muted-foreground' },
      reviewing: { label: '审核中', className: 'bg-info-muted text-info-muted-foreground' },
      published: { label: '已发布', className: 'bg-success-muted text-success-muted-foreground' },
      archived: { label: '已归档', className: 'bg-warning-muted text-warning-muted-foreground' },
    };
    return <Badge className={config[status].className}>{config[status].label}</Badge>;
  };

  const handleViewKnowledge = (item: KnowledgeItem) => {
    setSelectedKnowledge(item);
    setShowKnowledgeDetail(true);
  };

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

    // 模拟AI回答
    const answer = generateAnswer(currentQuestion);
    const now = safeNow();
    const newSession: QASession = {
      id: `qa_${now}`,
      question: currentQuestion,
      answer: answer.text,
      confidence: answer.confidence,
      sources: answer.sources,
      relatedCases: answer.cases,
      timestamp: formatDateTime(now),
      helpful: null,
    };

    setQAHistory([newSession, ...qaHistory]);
    setCurrentQuestion('');
    toast.success('回答已生成');
  };

  const generateAnswer = (question: string) => {
    // 简单的关键词匹配逻辑
    const lowerQ = question.toLowerCase();
    
    if (lowerQ.includes('番茄') && lowerQ.includes('灌溉')) {
      return {
        text: `根据知识库分析，番茄灌溉的最佳实践如下：

**开花期灌溉建议：**
1. **时机判断**：土壤湿度低于40%时需要灌溉
2. **最佳时间**：傍晚17:00-18:00或清晨6:00-7:00
3. **灌溉量计算**：(目标湿度60-70% - 当前湿度) × 地块面积 × 0.8-1.0

**注意事项：**
- 避开高温时段，减少蒸发损失
- 开花期是关键期，保持适宜湿度可提高坐果率15-20%
- 采用滴灌或喷灌方式效果更佳

相关案例显示，按此方法灌溉的成功率达到91%，平均提升坐果率18.5%。`,
        confidence: 0.92,
        sources: ['KNOW-2024-001'],
        cases: ['know_001'],
      };
    } else if (lowerQ.includes('黄瓜') && lowerQ.includes('病')) {
      return {
        text: `根据病虫害预警知识库，黄瓜常见病害预警如下：

**霜霉病预警**（准确率91%）：
- 触发条件：湿度>85% AND 温度18-24℃ AND 持续>6小时
- 防治措施：加强通风、降低湿度、预防性喷药

**白粉病预警**（准确率87%）：
- 触发条件：湿度60-80% AND 温度20-28℃ AND 通风不良
- 防治措施：改善通风、控制湿度、及时用药

**预警准确率分析**：
- 整体准确率：89%
- 误报率：8-10%
- 漏报率：9-13%

建议结合环境监测数据，提前3-5天采取预防措施。`,
        confidence: 0.88,
        sources: ['KNOW-2024-002'],
        cases: ['know_002'],
      };
    } else if (lowerQ.includes('玉米') && lowerQ.includes('施肥')) {
      return {
        text: `根据施肥决策案例库，玉米追肥方案如下：

**拔节期追肥方案**：
1. **养分诊断**：
   - 检测土壤氮素含量
   - 测量叶片SPAD值
   - 观察植株长势

2. **用量计算**：
   - 尿素：12-15kg/亩
   - 钾肥：5-8kg/亩
   - 根据土壤检测结果调整

3. **施用方法**：
   - 沟施+浇水（利用率最高）
   - 避免撒施（损失大）

**预期效果**：
- 产量提升：15%左右
- 投入产出比：1:3.5
- 成功率：94%

参考案例：5号田20亩玉米，采用此方案后产量从565kg/亩提升至650kg/亩，增收3000元。`,
        confidence: 0.90,
        sources: ['KNOW-2024-004'],
        cases: ['know_004'],
      };
    } else {
      return {
        text: `根据您的问题，我为您找到了以下相关信息：

当前知识库包含${knowledgeItems.length}条知识，涵盖：
- 应用场景知识
- 规则有效性分析
- 成功案例总结
- 决策模式识别
- 关键洞察提炼

建议：
1. 尝试更具体的问题，如"番茄开花期如何灌溉"
2. 浏览知识库中的成功案例
3. 查看案例推荐获取相似场景参考

如需更详细的帮助，请提供更多背景信息。`,
        confidence: 0.65,
        sources: [],
        cases: [],
      };
    }
  };

  const handleFeedback = (sessionId: string, helpful: boolean) => {
    setQAHistory(qaHistory.map(session => 
      session.id === sessionId ? { ...session, helpful } : session
    ));
    toast.success(helpful ? '感谢您的反馈！' : '我们会改进回答质量');
  };

  const handleCopyAnswer = async (answer: string) => {
    const success = await copyToClipboard(answer);
    if (success) {
      toast.success('回答已复制到剪贴板');
    } else {
      toast.error('复制失败，请重试');
    }
  };

  // 筛选知识
  const filteredKnowledge = knowledgeItems.filter(item => {
    if (filters.type !== 'all' && item.type !== filters.type) return false;
    if (filters.category !== 'all' && item.category !== filters.category) return false;
    if (filters.status !== 'all' && item.status !== filters.status) return false;
    if (filters.searchText && !item.title.toLowerCase().includes(filters.searchText.toLowerCase()) &&
        !item.content.toLowerCase().includes(filters.searchText.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-accent-muted to-accent-muted/50 border-accent">
        <div className="flex items-start gap-3">
          <Brain className="w-6 h-6 text-accent-foreground flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">AI知识自动生成与应用</h2>
            <p className="text-sm text-muted-foreground mb-3">
              自动抽取决策知识，形成结构化知识库，支持知识检索、案例推荐与智能问答
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Sparkles className="w-3 h-3 mr-1" />
                自动生成
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Database className="w-3 h-3 mr-1" />
                知识沉淀
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Search className="w-3 h-3 mr-1" />
                智能检索
              </Badge>
              <Badge variant="outline" className="bg-white">
                <MessageSquare className="w-3 h-3 mr-1" />
                智能问答
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-3 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">知识总量</div>
            <BookOpen className="w-5 h-5 text-accent-foreground" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.totalKnowledge}</div>
          <div className="text-xs text-muted-foreground">
            自动生成: {stats.autoGenerated}条
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">应用次数</div>
            <Activity className="w-5 h-5 text-info" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.totalUseCount}</div>
          <div className="text-xs text-muted-foreground">
            成功率: {stats.avgSuccessRate}%
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">知识质量</div>
            <TrendingUp className="w-5 h-5 text-success" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.avgConfidence}%</div>
          <div className="text-xs text-muted-foreground">
            平均置信度
          </div>
        </Card>
      </div>

      {/* Tab切换 */}
      <Tabs defaultValue="knowledge" className="space-y-6">
        <TabsList>
          <TabsTrigger value="knowledge">
            <Database className="w-4 h-4 mr-2" />
            知识库
          </TabsTrigger>
          <TabsTrigger value="recommendations">
            <Target className="w-4 h-4 mr-2" />
            案例推荐
          </TabsTrigger>
          <TabsTrigger value="qa">
            <MessageSquare className="w-4 h-4 mr-2" />
            智能问答
          </TabsTrigger>
        </TabsList>

        {/* 知识库 */}
        <TabsContent value="knowledge">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>知识库</h3>
              <div className="flex gap-2">
                <Button variant="outline" size="sm">
                  <RefreshCw className="w-4 h-4 mr-2" />
                  刷新
                </Button>
              </div>
            </div>

            {/* 筛选条件 */}
            <div className="grid grid-cols-4 gap-4 mb-4">
              <div>
                <Label>知识类型</Label>
                <Select value={filters.type} onValueChange={(value) => setFilters({ ...filters, type: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                    <SelectItem value="scenario">应用场景</SelectItem>
                    <SelectItem value="rule">规则分析</SelectItem>
                    <SelectItem value="case">成功案例</SelectItem>
                    <SelectItem value="pattern">识别模式</SelectItem>
                    <SelectItem value="insight">关键洞察</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>知识分类</Label>
                <Select value={filters.category} onValueChange={(value) => setFilters({ ...filters, category: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部分类</SelectItem>
                    <SelectItem value="灌溉决策">灌溉决策</SelectItem>
                    <SelectItem value="病虫害防治">病虫害防治</SelectItem>
                    <SelectItem value="施肥决策">施肥决策</SelectItem>
                    <SelectItem value="模型应用">模型应用</SelectItem>
                    <SelectItem value="决策优化">决策优化</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>状态</Label>
                <Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="published">已发布</SelectItem>
                    <SelectItem value="reviewing">审核中</SelectItem>
                    <SelectItem value="draft">草稿</SelectItem>
                  </SelectContent>
                </Select>
              </div>

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

            {/* 知识列表 */}
            <div className="space-y-4">
              {filteredKnowledge.map((item) => {
                const TypeIcon = getKnowledgeTypeIcon(item.type);
                return (
                  <div key={item.id} className="p-4 border rounded-lg hover:bg-accent transition-colors">
                    <div className="flex items-start gap-4">
                      <div className="w-12 h-12 rounded-lg bg-accent-muted flex items-center justify-center flex-shrink-0">
                        <TypeIcon className="w-6 h-6 text-accent-foreground" />
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-2">
                          <h4 className="truncate">{item.title}</h4>
                          {getStatusBadge(item.status)}
                          <Badge variant="outline" className="text-xs">
                            {getKnowledgeTypeName(item.type)}
                          </Badge>
                        </div>

                        <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                          {item.content.split('\n')[0]}
                        </p>

                        <div className="flex items-center gap-4 text-sm text-muted-foreground mb-3">
                          <div className="flex items-center gap-1">
                            <Zap className="w-3 h-3" />
                            置信度: {(item.confidence * 100).toFixed(0)}%
                          </div>
                          <div className="flex items-center gap-1">
                            <Target className="w-3 h-3" />
                            准确率: {(item.accuracy * 100).toFixed(0)}%
                          </div>
                          <div className="flex items-center gap-1">
                            <Users className="w-3 h-3" />
                            应用: {item.useCount}次
                          </div>
                          <div className="flex items-center gap-1">
                            <TrendingUp className="w-3 h-3" />
                            成功率: {(item.successRate * 100).toFixed(0)}%
                          </div>
                        </div>

                        <div className="flex items-center gap-2">
                          {item.tags.map((tag, idx) => (
                            <Badge key={idx} variant="outline" className="text-xs">
                              <Tag className="w-3 h-3 mr-1" />
                              {tag}
                            </Badge>
                          ))}
                        </div>
                      </div>

                      <div className="flex gap-2 flex-shrink-0">
                        <Button size="sm" variant="outline" onClick={() => handleViewKnowledge(item)}>
                          <Eye className="w-4 h-4 mr-1" />
                          查看
                        </Button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>
        </TabsContent>

        {/* 案例推荐 */}
        <TabsContent value="recommendations">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>案例推荐</h3>
              <Badge className="bg-info">
                基于当前决策上下文的智能推荐
              </Badge>
            </div>

            <div className="space-y-4">
              {recommendations.map((rec) => (
                <div key={rec.id} className="p-4 border rounded-lg bg-info-muted border-info/30">
                  <div className="flex items-start gap-4">
                    <div className="w-12 h-12 rounded-lg bg-info flex items-center justify-center flex-shrink-0">
                      <Award className="w-6 h-6 text-white" />
                    </div>
                    
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h4>{rec.caseTitle}</h4>
                        <Badge className="bg-green-600">
                          相似度: {(rec.similarity * 100).toFixed(0)}%
                        </Badge>
                      </div>

                      <div className="mb-3">
                        <div className="text-sm font-medium mb-1">匹配特征：</div>
                        <div className="flex flex-wrap gap-2">
                          {rec.matchedFeatures.map((feature, idx) => (
                            <Badge key={idx} variant="outline" className="text-xs bg-white">
                              <CheckCircle className="w-3 h-3 mr-1 text-green-500" />
                              {feature}
                            </Badge>
                          ))}
                        </div>
                      </div>

                      <div className="p-3 bg-white rounded-lg mb-3">
                        <div className="text-sm font-medium mb-1">应用理由：</div>
                        <p className="text-sm text-muted-foreground">{rec.applicableReason}</p>
                      </div>

                      <div className="p-3 bg-green-50 rounded-lg border border-green-200">
                        <div className="text-sm font-medium mb-1">预期效果：</div>
                        <p className="text-sm text-green-700">{rec.outcome}</p>
                      </div>
                    </div>

                    <Button onClick={() => {
                      const item = knowledgeItems.find(k => k.id === rec.caseId);
                      if (item) handleViewKnowledge(item);
                    }}>
                      <Eye className="w-4 h-4 mr-2" />
                      查看详情
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 智能问答 - AI对话样式 */}
        <TabsContent value="qa">
          <Card className="flex flex-col h-[calc(100vh-20rem)]">
            {/* 对话头部 */}
            <div className="p-4 border-b bg-gradient-to-r from-purple-50 to-blue-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-purple-600 flex items-center justify-center">
                  <Brain className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h3 className="mb-0">AI农业知识助手</h3>
                  <p className="text-sm text-muted-foreground">基于{knowledgeItems.length}条专业知识为您服务</p>
                </div>
              </div>
            </div>

            {/* 对话区域 */}
            <div className="flex-1 overflow-y-auto p-6 bg-muted">
              {qaHistory.length === 0 ? (
                <div className="h-full flex items-center justify-center">
                  <div className="text-center text-muted-foreground max-w-md">
                    <Sparkles className="w-16 h-16 mx-auto mb-4 text-purple-300" />
                    <h4 className="mb-2">开始与AI助手对话</h4>
                    <p className="text-sm mb-4">
                      我可以回答关于灌溉、施肥、病虫害防治等农业问题
                    </p>
                    <div className="flex flex-wrap gap-2 justify-center">
                      <Badge variant="outline" className="cursor-pointer hover:bg-purple-50" onClick={() => setCurrentQuestion('番茄开花期如何灌溉？')}>
                        番茄开花期如何灌溉？
                      </Badge>
                      <Badge variant="outline" className="cursor-pointer hover:bg-purple-50" onClick={() => setCurrentQuestion('黄瓜病虫害如何预防？')}>
                        黄瓜病虫害如何预防？
                      </Badge>
                      <Badge variant="outline" className="cursor-pointer hover:bg-purple-50" onClick={() => setCurrentQuestion('玉米追肥最佳时间？')}>
                        玉米追肥最佳时间？
                      </Badge>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="space-y-6 max-w-4xl mx-auto">
                  {[...qaHistory].reverse().map((session) => (
                    <div key={session.id} className="space-y-4">
                      {/* 用户问题 */}
                      <div className="flex gap-3 justify-end">
                        <div className="flex-1 max-w-2xl">
                          <div className="bg-blue-600 text-white p-4 rounded-2xl rounded-tr-sm">
                            <p>{session.question}</p>
                          </div>
                          <div className="text-xs text-muted-foreground mt-1 text-right">
                            {session.timestamp}
                          </div>
                        </div>
                        <div className="w-10 h-10 rounded-full bg-blue-600 flex items-center justify-center flex-shrink-0">
                          <Users className="w-5 h-5 text-white" />
                        </div>
                      </div>

                      {/* AI回答 */}
                      <div className="flex gap-3">
                        <div className="w-10 h-10 rounded-full bg-gradient-to-br from-purple-600 to-purple-700 flex items-center justify-center flex-shrink-0">
                          <Brain className="w-5 h-5 text-white" />
                        </div>
                        <div className="flex-1 max-w-2xl">
                          <div className="bg-white border border-gray-200 p-4 rounded-2xl rounded-tl-sm shadow-sm">
                            <div className="flex items-center gap-2 mb-3">
                              <Badge className="bg-purple-600">
                                <Sparkles className="w-3 h-3 mr-1" />
                                AI回答
                              </Badge>
                              <Badge variant="outline" className="text-xs">
                                置信度: {(session.confidence * 100).toFixed(0)}%
                              </Badge>
                            </div>
                            
                            <div className="prose prose-sm max-w-none">
                              <pre className="whitespace-pre-wrap font-sans text-sm text-gray-700">
                                {session.answer}
                              </pre>
                            </div>

                            {session.sources.length > 0 && (
                              <div className="mt-4 pt-3 border-t border-gray-100">
                                <div className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
                                  <FileText className="w-3 h-3" />
                                  参考知识:
                                </div>
                                <div className="flex flex-wrap gap-2">
                                  {session.sources.map((source, idx) => (
                                    <Badge key={idx} variant="outline" className="text-xs">
                                      {source}
                                    </Badge>
                                  ))}
                                </div>
                              </div>
                            )}

                            <div className="flex items-center gap-2 mt-4 pt-3 border-t border-gray-100">
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => handleCopyAnswer(session.answer)}
                                className="h-8"
                              >
                                <Copy className="w-3 h-3 mr-1" />
                                复制
                              </Button>
                              <div className="flex-1" />
                              <span className="text-xs text-muted-foreground">有帮助吗？</span>
                              <Button
                                size="sm"
                                variant={session.helpful === true ? 'default' : 'ghost'}
                                onClick={() => handleFeedback(session.id, true)}
                                className="h-8 w-8 p-0"
                              >
                                <ThumbsUp className="w-3 h-3" />
                              </Button>
                              <Button
                                size="sm"
                                variant={session.helpful === false ? 'default' : 'ghost'}
                                onClick={() => handleFeedback(session.id, false)}
                                className="h-8 w-8 p-0"
                              >
                                <ThumbsDown className="w-3 h-3" />
                              </Button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 输入区域 */}
            <div className="p-4 border-t bg-white">
              <div className="max-w-4xl mx-auto">
                <div className="flex gap-3">
                  <Textarea
                    placeholder="输入您的问题，例如：番茄开花期如何灌溉？"
                    value={currentQuestion}
                    onChange={(e) => setCurrentQuestion(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        handleAskQuestion();
                      }
                    }}
                    rows={2}
                    className="flex-1 resize-none"
                  />
                  <Button 
                    onClick={handleAskQuestion} 
                    className="bg-purple-600 hover:bg-purple-700 px-6"
                    disabled={!currentQuestion.trim()}
                  >
                    <Send className="w-4 h-4" />
                  </Button>
                </div>
                <div className="text-xs text-muted-foreground mt-2 text-center">
                  按 Enter 发送，Shift + Enter 换行
                </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>
              查看知识的完整内容和应用信息
            </DialogDescription>
          </DialogHeader>

          {selectedKnowledge && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">知识编号</div>
                    <div className="font-medium">{selectedKnowledge.knowledgeNo}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">知识类型</div>
                    <div className="font-medium">{getKnowledgeTypeName(selectedKnowledge.type)}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">知识分类</div>
                    <div className="font-medium">{selectedKnowledge.category}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">生成方式</div>
                    <div className="font-medium">
                      {selectedKnowledge.sourceType === 'auto' ? 'AI自动生成' : '手工录入'}
                    </div>
                  </div>
                </div>
              </div>

              {/* 知识内容 */}
              <div>
                <h4 className="mb-3">知识内容</h4>
                <div className="p-4 bg-muted rounded-lg">
                  <pre className="whitespace-pre-wrap font-sans text-sm">
                    {selectedKnowledge.content}
                  </pre>
                </div>
              </div>

              {/* 质量指标 */}
              <div>
                <h4 className="mb-3">质量指标</h4>
                <div className="grid grid-cols-4 gap-4">
                  <div className="p-4 bg-purple-50 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">置信度</div>
                    <div className="text-2xl font-bold text-purple-600">
                      {(selectedKnowledge.confidence * 100).toFixed(0)}%
                    </div>
                  </div>
                  <div className="p-4 bg-blue-50 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">准确率</div>
                    <div className="text-2xl font-bold text-blue-600">
                      {(selectedKnowledge.accuracy * 100).toFixed(0)}%
                    </div>
                  </div>
                  <div className="p-4 bg-green-50 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">应用次数</div>
                    <div className="text-2xl font-bold text-green-600">
                      {selectedKnowledge.useCount}
                    </div>
                  </div>
                  <div className="p-4 bg-orange-50 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">成功率</div>
                    <div className="text-2xl font-bold text-orange-600">
                      {(selectedKnowledge.successRate * 100).toFixed(0)}%
                    </div>
                  </div>
                </div>
              </div>

              {/* 适用条件 */}
              {selectedKnowledge.conditions && (
                <div>
                  <h4 className="mb-3">适用条件</h4>
                  <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                    <pre className="text-sm overflow-x-auto">
                      {JSON.stringify(selectedKnowledge.conditions, null, 2)}
                    </pre>
                  </div>
                </div>
              )}

              {/* 应用效果 */}
              {selectedKnowledge.impact && (
                <div>
                  <h4 className="mb-3">应用效果</h4>
                  <div className="grid grid-cols-3 gap-4">
                    <div className="p-4 bg-green-50 rounded-lg border border-green-200 text-center">
                      <div className="text-xs text-muted-foreground mb-1">平均提升</div>
                      <div className="text-2xl font-bold text-green-600">
                        {selectedKnowledge.impact.avgImprovement}%
                      </div>
                    </div>
                    <div className="p-4 bg-blue-50 rounded-lg border border-blue-200 text-center">
                      <div className="text-xs text-muted-foreground mb-1">应用案例</div>
                      <div className="text-2xl font-bold text-blue-600">
                        {selectedKnowledge.impact.casesApplied}
                      </div>
                    </div>
                    <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200 text-center">
                      <div className="text-xs text-muted-foreground mb-1">用户评分</div>
                      <div className="text-2xl font-bold text-yellow-600">
                        {selectedKnowledge.impact.userRating}/5.0
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* 标签 */}
              <div>
                <h4 className="mb-3">标签</h4>
                <div className="flex flex-wrap gap-2">
                  {selectedKnowledge.tags.map((tag, idx) => (
                    <Badge key={idx} variant="outline">
                      <Tag className="w-3 h-3 mr-1" />
                      {tag}
                    </Badge>
                  ))}
                </div>
              </div>
            </div>
          )}

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