import { useState, useEffect } 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 { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Checkbox } from '../ui/checkbox';
import { RichTextEditor } from './RichTextEditor';
import {
  BookOpen,
  Plus,
  Edit,
  Trash2,
  Eye,
  Search,
  Filter,
  Download,
  Upload,
  FileText,
  Image as ImageIcon,
  Video,
  Link2,
  Tag,
  Layers,
  Calendar,
  User,
  Star,
  Share2,
  BookMarked,
  FileQuestion,
  Lightbulb,
  Bug,
  Sprout,
  Leaf,
  Target,
  GraduationCap,
  Bookmark,
  Heart,
  MessageSquare,
  TrendingUp,
  Database,
  FolderTree,
  Hash,
  AlertCircle,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface OperationKnowledgeProps {
  activePath?: string;
}

type ContentType = '文本' | '图文教程' | '视频' | '病虫害图谱' | '解决方案' | 'FAQ' | '文献';
type KnowledgeStatus = '草稿' | '已发布' | '已归档';

interface KnowledgeItem {
  id: string;
  title: string;
  type: ContentType;
  category: string;
  tags: string[];
  author: string;
  createdAt: string;
  updatedAt: string;
  views: number;
  likes: number;
  bookmarks: number;
  status: KnowledgeStatus;
  content: string;
  media?: {
    images?: string[];
    videos?: string[];
    attachments?: { name: string; url: string }[];
  };
  metadata: {
    crop?: string;
    growthStage?: string;
    problemType?: string;
    operationType?: string;
    difficulty?: string;
  };
}

interface Category {
  id: string;
  name: string;
  icon: string;
  color: string;
  count: number;
  subcategories?: Category[];
}

interface Tag {
  id: string;
  name: string;
  category: string;
  count: number;
  color: string;
}

// 辅助函数：从HTML中提取纯文本
const stripHtmlTags = (html: string): string => {
  const tmp = document.createElement('div');
  tmp.innerHTML = html;
  return tmp.textContent || tmp.innerText || '';
};

export function OperationKnowledge({ activePath }: OperationKnowledgeProps) {
  const [activeTab, setActiveTab] = useState('management');
  const [showKnowledgeDialog, setShowKnowledgeDialog] = useState(false);
  const [selectedKnowledge, setSelectedKnowledge] = useState<KnowledgeItem | null>(null);
  const [filterType, setFilterType] = useState<string>('all');
  const [filterCategory, setFilterCategory] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [viewingKnowledge, setViewingKnowledge] = useState<KnowledgeItem | null>(null);
  
  // 分类管理状态
  const [showCategoryDialog, setShowCategoryDialog] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [categoryFormData, setCategoryFormData] = useState({
    name: '',
    icon: '',
    color: 'bg-info-muted text-info-muted-foreground',
  });

  // 标签管理状态
  const [showTagDialog, setShowTagDialog] = useState(false);
  const [editingTag, setEditingTag] = useState<Tag | null>(null);
  const [tagFormData, setTagFormData] = useState({
    name: '',
    category: '作物',
    color: 'bg-success-muted text-success-muted-foreground',
  });

  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    type: '文本' as ContentType,
    category: '',
    tags: '',
    content: '',
    crop: '',
    growthStage: '',
    problemType: '',
    operationType: '',
    difficulty: '简单',
    externalLink: '',
    reference: '',
  });

  // 选中的标签ID列表
  const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/management')) {
        setActiveTab('management');
      } else if (activePath.includes('/category')) {
        setActiveTab('category');
      } else if (activePath.includes('/search')) {
        setActiveTab('search');
      }
    }
  }, [activePath]);

  // 模拟知识库数据
  const [knowledgeItems, setKnowledgeItems] = useState<KnowledgeItem[]>([
    {
      id: 'kb-1',
      title: '水稻播种技术要点',
      type: '图文教程',
      category: '种植技术',
      tags: ['水稻', '播种', '春季', '育秧'],
      author: '张农技师',
      createdAt: '2024-02-15',
      updatedAt: '2024-03-01',
      views: 1250,
      likes: 89,
      bookmarks: 42,
      status: '已发布',
      content: '水稻播种是水稻生产的关键环节...',
      media: {
        images: ['seed1.jpg', 'seed2.jpg', 'seed3.jpg'],
        attachments: [{ name: '水稻播种技术规程.pdf', url: '#' }],
      },
      metadata: {
        crop: '水稻',
        growthStage: '播种期',
        operationType: '播种',
        difficulty: '中等',
      },
    },
    {
      id: 'kb-2',
      title: '水稻稻飞虱防治方案',
      type: '病虫害图谱',
      category: '病虫害防治',
      tags: ['水稻', '稻飞虱', '虫害', '防治'],
      author: '李植保专家',
      createdAt: '2024-03-10',
      updatedAt: '2024-03-15',
      views: 856,
      likes: 67,
      bookmarks: 38,
      status: '已发布',
      content: '稻飞虱是水稻主要害虫之一...',
      media: {
        images: ['pest1.jpg', 'pest2.jpg', 'pest3.jpg', 'pest4.jpg'],
      },
      metadata: {
        crop: '水稻',
        growthStage: '分蘖期',
        problemType: '虫害',
        difficulty: '较难',
      },
    },
    {
      id: 'kb-3',
      title: '如何判断水稻最佳收获时期？',
      type: 'FAQ',
      category: '常见问题',
      tags: ['水稻', '采收', '成熟期'],
      author: '王农艺师',
      createdAt: '2024-03-01',
      updatedAt: '2024-03-01',
      views: 542,
      likes: 34,
      bookmarks: 18,
      status: '已发布',
      content: 'Q: 如何判断水稻最佳收获时期？\nA: 主要观察以下几个指标...',
      metadata: {
        crop: '水稻',
        growthStage: '成熟期',
        operationType: '采收',
        difficulty: '简单',
      },
    },
    {
      id: 'kb-4',
      title: '水稻精准施肥技术视频教程',
      type: '视频',
      category: '施肥技术',
      tags: ['水稻', '施肥', '精准农业'],
      author: '赵教授',
      createdAt: '2024-02-20',
      updatedAt: '2024-02-20',
      views: 2150,
      likes: 156,
      bookmarks: 89,
      status: '已发布',
      content: '本视频详细讲解水稻生长期间的精准施肥技术...',
      media: {
        videos: ['fertilizer_tutorial.mp4'],
        attachments: [{ name: '施肥配方表.xlsx', url: '#' }],
      },
      metadata: {
        crop: '水稻',
        growthStage: '全生育期',
        operationType: '施肥',
        difficulty: '中等',
      },
    },
    {
      id: 'kb-5',
      title: '水稻病害综合防治解决方案',
      type: '解决方案',
      category: '病虫害防治',
      tags: ['水稻', '病害', '综合防治'],
      author: '陈专家',
      createdAt: '2024-03-05',
      updatedAt: '2024-03-12',
      views: 1024,
      likes: 78,
      bookmarks: 56,
      status: '已发布',
      content: '针对水稻主要病害的综合防治方案...',
      media: {
        images: ['disease1.jpg', 'disease2.jpg'],
        attachments: [
          { name: '病害防治方案.pdf', url: '#' },
          { name: '农药使用指南.pdf', url: '#' },
        ],
      },
      metadata: {
        crop: '水稻',
        problemType: '病害',
        difficulty: '较难',
      },
    },
    {
      id: 'kb-6',
      title: '水稻高产栽培技术研究进展',
      type: '文献',
      category: '科研文献',
      tags: ['水稻', '高产', '科研'],
      author: '农业科学院',
      createdAt: '2024-01-15',
      updatedAt: '2024-01-15',
      views: 456,
      likes: 23,
      bookmarks: 34,
      status: '已发布',
      content: '摘要：本文综述了近年来水稻高产栽培技术的研究进展...',
      media: {
        attachments: [{ name: '研究论文.pdf', url: '#' }],
      },
      metadata: {
        crop: '水稻',
        difficulty: '专业',
      },
    },
  ]);

  // 分类体系
  const [categories, setCategories] = useState<Category[]>([
    {
      id: 'cat-1',
      name: '种植技术',
      icon: '🌱',
      color: 'bg-success-muted text-success-muted-foreground',
      count: 45,
      subcategories: [
        { id: 'cat-1-1', name: '播种育秧', icon: '🌾', color: 'bg-success-muted', count: 12 },
        { id: 'cat-1-2', name: '田间管理', icon: '🚜', color: 'bg-success-muted', count: 18 },
        { id: 'cat-1-3', name: '采收技术', icon: '🌾', color: 'bg-success-muted', count: 15 },
      ],
    },
    {
      id: 'cat-2',
      name: '病虫害防治',
      icon: '🐛',
      color: 'bg-error-muted text-error-muted-foreground',
      count: 38,
      subcategories: [
        { id: 'cat-2-1', name: '病害识别', icon: '🔍', color: 'bg-error-muted', count: 15 },
        { id: 'cat-2-2', name: '虫害防治', icon: '🦗', color: 'bg-error-muted', count: 12 },
        { id: 'cat-2-3', name: '综合防治', icon: '🛡️', color: 'bg-error-muted', count: 11 },
      ],
    },
    {
      id: 'cat-3',
      name: '施肥技术',
      icon: '💊',
      color: 'bg-warning-muted text-warning-muted-foreground',
      count: 32,
      subcategories: [
        { id: 'cat-3-1', name: '基肥施用', icon: '🌾', color: 'bg-warning-muted', count: 10 },
        { id: 'cat-3-2', name: '追肥技术', icon: '💧', color: 'bg-warning-muted', count: 12 },
        { id: 'cat-3-3', name: '叶面肥', icon: '🍃', color: 'bg-warning-muted', count: 10 },
      ],
    },
    {
      id: 'cat-4',
      name: '灌溉排水',
      icon: '💧',
      color: 'bg-info-muted text-info-muted-foreground',
      count: 28,
    },
    {
      id: 'cat-5',
      name: '常见问题',
      icon: '❓',
      color: 'bg-muted text-muted-foreground',
      count: 56,
    },
    {
      id: 'cat-6',
      name: '科研文献',
      icon: '📚',
      color: 'bg-muted text-muted-foreground',
      count: 24,
    },
  ]);

  // 标签体系
  const [tags, setTags] = useState<Tag[]>([
    // 作物标签
    { id: 'tag-1', name: '水稻', category: '作物', count: 89, color: 'bg-success-muted text-success-muted-foreground' },
    { id: 'tag-2', name: '玉米', category: '作物', count: 45, color: 'bg-warning-muted text-warning-muted-foreground' },
    { id: 'tag-3', name: '小麦', category: '作物', count: 34, color: 'bg-warning-muted text-warning-muted-foreground' },
    { id: 'tag-4', name: '蔬菜', category: '作物', count: 56, color: 'bg-success-muted text-success-muted-foreground' },
    
    // 生育期标签
    { id: 'tag-5', name: '播种期', category: '生育期', count: 28, color: 'bg-info-muted text-info-muted-foreground' },
    { id: 'tag-6', name: '苗期', category: '生育期', count: 32, color: 'bg-info-muted text-info-muted-foreground' },
    { id: 'tag-7', name: '分蘖期', category: '生育期', count: 24, color: 'bg-info-muted text-info-muted-foreground' },
    { id: 'tag-8', name: '拔节期', category: '生育期', count: 18, color: 'bg-success-muted text-success-muted-foreground' },
    { id: 'tag-9', name: '抽穗期', category: '生育期', count: 22, color: 'bg-success-muted text-success-muted-foreground' },
    { id: 'tag-10', name: '成熟期', category: '生育期', count: 26, color: 'bg-warning-muted text-warning-muted-foreground' },
    
    // 问题类型标签
    { id: 'tag-11', name: '病害', category: '问题类型', count: 34, color: 'bg-error-muted text-error-muted-foreground' },
    { id: 'tag-12', name: '虫害', category: '问题类型', count: 28, color: 'bg-error-muted text-error-muted-foreground' },
    { id: 'tag-13', name: '草害', category: '问题类型', count: 16, color: 'bg-muted text-muted-foreground' },
    { id: 'tag-14', name: '营养不良', category: '问题类型', count: 20, color: 'bg-warning-muted text-warning-muted-foreground' },
    
    // 农事类型标签
    { id: 'tag-15', name: '播种', category: '农事类型', count: 42, color: 'bg-success-muted text-success-muted-foreground' },
    { id: 'tag-16', name: '施肥', category: '农事类型', count: 38, color: 'bg-warning-muted text-warning-muted-foreground' },
    { id: 'tag-17', name: '灌溉', category: '农事类型', count: 32, color: 'bg-info-muted text-info-muted-foreground' },
    { id: 'tag-18', name: '除草', category: '农事类型', count: 24, color: 'bg-muted text-muted-foreground' },
    { id: 'tag-19', name: '采收', category: '农事类型', count: 28, color: 'bg-warning-muted text-warning-muted-foreground' },
  ]);

  const getTypeIcon = (type: ContentType) => {
    switch (type) {
      case '文本': return <FileText className="w-4 h-4" />;
      case '图文教程': return <BookOpen className="w-4 h-4" />;
      case '视频': return <Video className="w-4 h-4" />;
      case '病虫害图谱': return <Bug className="w-4 h-4" />;
      case '解决方案': return <Lightbulb className="w-4 h-4" />;
      case 'FAQ': return <FileQuestion className="w-4 h-4" />;
      case '文献': return <GraduationCap className="w-4 h-4" />;
      default: return <FileText className="w-4 h-4" />;
    }
  };

  const getTypeColor = (type: ContentType) => {
    switch (type) {
      case '文本': return 'bg-gray-100 text-gray-800';
      case '图文教程': return 'bg-blue-100 text-blue-800';
      case '视频': return 'bg-purple-100 text-purple-800';
      case '病虫害图谱': return 'bg-red-100 text-red-800';
      case '解决方案': return 'bg-green-100 text-green-800';
      case 'FAQ': return 'bg-yellow-100 text-yellow-800';
      case '文献': return 'bg-indigo-100 text-indigo-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const handleCreateKnowledge = () => {
    setSelectedKnowledge(null);
    setFormData({
      title: '',
      type: '文本',
      category: '',
      tags: '',
      content: '',
      crop: '',
      growthStage: '',
      problemType: '',
      operationType: '',
      difficulty: '简单',
      externalLink: '',
      reference: '',
    });
    setSelectedTagIds([]);
    setShowKnowledgeDialog(true);
  };

  const handleEditKnowledge = (item: KnowledgeItem) => {
    setSelectedKnowledge(item);
    setFormData({
      title: item.title,
      type: item.type,
      category: item.category,
      tags: item.tags.join(', '),
      content: item.content,
      crop: item.metadata.crop || '',
      growthStage: item.metadata.growthStage || '',
      problemType: item.metadata.problemType || '',
      operationType: item.metadata.operationType || '',
      difficulty: item.metadata.difficulty || '简单',
      externalLink: '',
      reference: '',
    });
    
    // 根据已有标签名称找到对应的标签ID
    const tagIds = tags
      .filter(tag => item.tags.includes(tag.name))
      .map(tag => tag.id);
    setSelectedTagIds(tagIds);
    
    setShowKnowledgeDialog(true);
  };

  const handleSaveKnowledge = () => {
    if (!formData.title || !formData.category || !formData.content) {
      toast.error('请填写必填项');
      return;
    }

    // 从选中的标签ID获取标签名称
    const selectedTagNames = tags
      .filter(tag => selectedTagIds.includes(tag.id))
      .map(tag => tag.name);

    const newKnowledge: KnowledgeItem = {
      id: selectedKnowledge?.id || `kb-${Date.now()}`,
      title: formData.title,
      type: formData.type,
      category: formData.category,
      tags: selectedTagNames,
      author: selectedKnowledge?.author || '当前用户',
      createdAt: selectedKnowledge?.createdAt || new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0],
      views: selectedKnowledge?.views || 0,
      likes: selectedKnowledge?.likes || 0,
      bookmarks: selectedKnowledge?.bookmarks || 0,
      status: '已发布',
      content: formData.content,
      metadata: {
        crop: formData.crop,
        growthStage: formData.growthStage,
        problemType: formData.problemType,
        operationType: formData.operationType,
        difficulty: formData.difficulty,
      },
    };

    if (selectedKnowledge) {
      setKnowledgeItems(knowledgeItems.map(item => 
        item.id === selectedKnowledge.id ? newKnowledge : item
      ));
      toast.success('知识内容已更新');
    } else {
      setKnowledgeItems([newKnowledge, ...knowledgeItems]);
      toast.success('知识内容已创建');
    }

    setShowKnowledgeDialog(false);
  };

  const handleDeleteKnowledge = (id: string) => {
    setKnowledgeItems(knowledgeItems.filter(item => item.id !== id));
    toast.success('知识内容已删除');
  };

  const handleViewKnowledge = (item: KnowledgeItem) => {
    // 增加浏览量
    setKnowledgeItems(knowledgeItems.map(k =>
      k.id === item.id ? { ...k, views: k.views + 1 } : k
    ));
    setViewingKnowledge(item);
    setShowViewDialog(true);
  };

  const handleLike = (id: string) => {
    setKnowledgeItems(knowledgeItems.map(item =>
      item.id === id ? { ...item, likes: item.likes + 1 } : item
    ));
    toast.success('已点赞');
  };

  const handleBookmark = (id: string) => {
    setKnowledgeItems(knowledgeItems.map(item =>
      item.id === id ? { ...item, bookmarks: item.bookmarks + 1 } : item
    ));
    toast.success('已收藏');
  };

  // ========== 分类管理功能 ==========
  const handleCreateCategory = () => {
    setEditingCategory(null);
    setCategoryFormData({
      name: '',
      icon: '',
      color: 'bg-blue-100 text-blue-800',
    });
    setShowCategoryDialog(true);
  };

  const handleEditCategory = (category: Category) => {
    setEditingCategory(category);
    setCategoryFormData({
      name: category.name,
      icon: category.icon,
      color: category.color,
    });
    setShowCategoryDialog(true);
  };

  const handleSaveCategory = () => {
    if (!categoryFormData.name || !categoryFormData.icon) {
      toast.error('请填写分类名称和图标');
      return;
    }

    if (editingCategory) {
      // 编辑分类
      setCategories(categories.map(cat =>
        cat.id === editingCategory.id
          ? { ...cat, name: categoryFormData.name, icon: categoryFormData.icon, color: categoryFormData.color }
          : cat
      ));
      toast.success('分类已更新');
    } else {
      // 新增分类
      const newCategory: Category = {
        id: `cat-${Date.now()}`,
        name: categoryFormData.name,
        icon: categoryFormData.icon,
        color: categoryFormData.color,
        count: 0,
      };
      setCategories([...categories, newCategory]);
      toast.success('分类已创建');
    }

    setShowCategoryDialog(false);
  };

  const handleDeleteCategory = (id: string) => {
    const category = categories.find(c => c.id === id);
    if (category && category.count > 0) {
      toast.error(`无法删除：该分类下还有 ${category.count} 篇知识内容`);
      return;
    }
    setCategories(categories.filter(cat => cat.id !== id));
    toast.success('分类已删除');
  };

  // ========== 标签管理功能 ==========
  const handleCreateTag = () => {
    setEditingTag(null);
    setTagFormData({
      name: '',
      category: '作物',
      color: 'bg-green-100 text-green-800',
    });
    setShowTagDialog(true);
  };

  const handleEditTag = (tag: Tag) => {
    setEditingTag(tag);
    setTagFormData({
      name: tag.name,
      category: tag.category,
      color: tag.color,
    });
    setShowTagDialog(true);
  };

  const handleSaveTag = () => {
    if (!tagFormData.name) {
      toast.error('请填写标签名称');
      return;
    }

    if (editingTag) {
      // 编辑标签
      setTags(tags.map(tag =>
        tag.id === editingTag.id
          ? { ...tag, name: tagFormData.name, category: tagFormData.category, color: tagFormData.color }
          : tag
      ));
      toast.success('标签已更新');
    } else {
      // 新增标签
      const newTag: Tag = {
        id: `tag-${Date.now()}`,
        name: tagFormData.name,
        category: tagFormData.category,
        color: tagFormData.color,
        count: 0,
      };
      setTags([...tags, newTag]);
      toast.success('标签已创建');
    }

    setShowTagDialog(false);
  };

  const handleDeleteTag = (id: string) => {
    const tag = tags.find(t => t.id === id);
    if (tag && tag.count > 0) {
      toast.error(`无法删除：有 ${tag.count} 篇知识使用了此标签`);
      return;
    }
    setTags(tags.filter(t => t.id !== id));
    toast.success('标签已删除');
  };

  const filteredKnowledge = knowledgeItems.filter(item => {
    if (filterType !== 'all' && item.type !== filterType) return false;
    if (filterCategory !== 'all' && item.category !== filterCategory) return false;
    if (filterStatus !== 'all' && item.status !== filterStatus) return false;
    if (searchQuery && !item.title.toLowerCase().includes(searchQuery.toLowerCase()) &&
        !stripHtmlTags(item.content).toLowerCase().includes(searchQuery.toLowerCase()) &&
        !item.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()))) {
      return false;
    }
    return true;
  });

  // 统计数据
  const totalKnowledge = knowledgeItems.length;
  const totalViews = knowledgeItems.reduce((sum, item) => sum + item.views, 0);
  const totalLikes = knowledgeItems.reduce((sum, item) => sum + item.likes, 0);
  const totalBookmarks = knowledgeItems.reduce((sum, item) => sum + item.bookmarks, 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">农事知识库</h2>
          <p className="text-muted-foreground">
            多模态知识内容管理、分类标签与智能检索
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <Upload className="w-4 h-4 mr-2" />
            批量导入
          </Button>
          <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateKnowledge}>
            <Plus className="w-4 h-4 mr-2" />
            新增知识
          </Button>
        </div>
      </div>

      {/* 统计概览 */}
      <div className="grid 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-green-600">{totalKnowledge}</p>
            </div>
            <BookOpen className="w-12 h-12 text-green-600 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-blue-600">{totalViews}</p>
            </div>
            <Eye className="w-12 h-12 text-blue-600 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-purple-600">{totalLikes}</p>
            </div>
            <Heart className="w-12 h-12 text-purple-600 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-orange-600">{totalBookmarks}</p>
            </div>
            <Bookmark className="w-12 h-12 text-orange-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="management">多模态知识内容管理</TabsTrigger>
          <TabsTrigger value="category">分类与标签</TabsTrigger>
          <TabsTrigger value="search">智能检索</TabsTrigger>
        </TabsList>

        {/* 多模态知识内容管理 */}
        <TabsContent value="management" className="space-y-4">
          {/* 内容类型说明 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Database className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">多模态知识内容支持：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>结构化文本</strong>: 标准化的技术文档、操作规程</li>
                  <li>• <strong>图文教程</strong>: 图片+文字的详细操作指南</li>
                  <li>• <strong>专家视频</strong>: 农技专家录制的教学视频</li>
                  <li>• <strong>病虫害图谱</strong>: 病虫害识别图片库，支持对比学习</li>
                  <li>• <strong>解决方案</strong>: 针对具体问题的系统性解决方案</li>
                  <li>• <strong>常见问答(FAQ)</strong>: 农户常见问题及答案</li>
                  <li>• <strong>外部权威文献</strong>: 科研论文、政策文件等</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 筛选器 */}
          <Card className="p-4">
            <div className="flex items-center gap-4">
              <Filter className="w-4 h-4 text-muted-foreground" />
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="内容类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="文本">文本</SelectItem>
                  <SelectItem value="图文教程">图文教程</SelectItem>
                  <SelectItem value="视频">视频</SelectItem>
                  <SelectItem value="病虫害图谱">病虫害图谱</SelectItem>
                  <SelectItem value="解决方案">解决方案</SelectItem>
                  <SelectItem value="FAQ">FAQ</SelectItem>
                  <SelectItem value="文献">文献</SelectItem>
                </SelectContent>
              </Select>

              <Select value={filterCategory} onValueChange={setFilterCategory}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="分类" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部分类</SelectItem>
                  {categories.map(cat => (
                    <SelectItem key={cat.id} value={cat.name}>
                      {cat.icon} {cat.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="草稿">草稿</SelectItem>
                  <SelectItem value="已发布">已发布</SelectItem>
                  <SelectItem value="已归档">已归档</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </Card>

          {/* 知识内容列表 */}
          <div className="grid grid-cols-2 gap-4">
            {filteredKnowledge.map(item => (
              <Card key={item.id} className="p-6 hover:shadow-lg transition-shadow">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3 flex-1">
                    <div className={`p-2 rounded-lg ${getTypeColor(item.type)}`}>
                      {getTypeIcon(item.type)}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <h4 className="flex-1">{item.title}</h4>
                        <Badge variant="outline">
                          {item.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground mb-2">
                        {item.category}
                      </p>
                      <div className="flex flex-wrap gap-1 mb-2">
                        {item.tags.slice(0, 3).map(tag => (
                          <Badge key={tag} variant="outline" className="text-xs">
                            <Hash className="w-2 h-2 mr-1" />
                            {tag}
                          </Badge>
                        ))}
                        {item.tags.length > 3 && (
                          <Badge variant="outline" className="text-xs">
                            +{item.tags.length - 3}
                          </Badge>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                <p className="text-sm text-muted-foreground mb-4 line-clamp-2">
                  {stripHtmlTags(item.content)}
                </p>

                {/* 媒体预览 */}
                {item.media && (
                  <div className="mb-4">
                    {item.media.images && item.media.images.length > 0 && (
                      <div className="flex gap-2 mb-2">
                        <ImageIcon className="w-4 h-4 text-blue-600" />
                        <span className="text-sm text-muted-foreground">
                          {item.media.images.length} 张图片
                        </span>
                      </div>
                    )}
                    {item.media.videos && item.media.videos.length > 0 && (
                      <div className="flex gap-2 mb-2">
                        <Video className="w-4 h-4 text-purple-600" />
                        <span className="text-sm text-muted-foreground">
                          {item.media.videos.length} 个视频
                        </span>
                      </div>
                    )}
                    {item.media.attachments && item.media.attachments.length > 0 && (
                      <div className="flex gap-2">
                        <Link2 className="w-4 h-4 text-gray-600" />
                        <span className="text-sm text-muted-foreground">
                          {item.media.attachments.length} 个附件
                        </span>
                      </div>
                    )}
                  </div>
                )}

                {/* 元数据 */}
                <div className="grid grid-cols-2 gap-2 mb-4 p-3 bg-gray-50 rounded-lg">
                  {item.metadata.crop && (
                    <div className="text-xs">
                      <span className="text-muted-foreground">作物: </span>
                      <span className="font-medium">{item.metadata.crop}</span>
                    </div>
                  )}
                  {item.metadata.growthStage && (
                    <div className="text-xs">
                      <span className="text-muted-foreground">生育期: </span>
                      <span className="font-medium">{item.metadata.growthStage}</span>
                    </div>
                  )}
                  {item.metadata.operationType && (
                    <div className="text-xs">
                      <span className="text-muted-foreground">农事类型: </span>
                      <span className="font-medium">{item.metadata.operationType}</span>
                    </div>
                  )}
                  {item.metadata.difficulty && (
                    <div className="text-xs">
                      <span className="text-muted-foreground">难度: </span>
                      <span className="font-medium">{item.metadata.difficulty}</span>
                    </div>
                  )}
                </div>

                {/* 统计信息 */}
                <div className="flex items-center justify-between text-sm text-muted-foreground mb-4">
                  <div className="flex items-center gap-4">
                    <span className="flex items-center gap-1">
                      <Eye className="w-3 h-3" />
                      {item.views}
                    </span>
                    <span className="flex items-center gap-1">
                      <Heart className="w-3 h-3" />
                      {item.likes}
                    </span>
                    <span className="flex items-center gap-1">
                      <Bookmark className="w-3 h-3" />
                      {item.bookmarks}
                    </span>
                  </div>
                  <div className="flex items-center gap-1">
                    <User className="w-3 h-3" />
                    {item.author}
                  </div>
                </div>

                {/* 操作按钮 */}
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" className="flex-1" onClick={() => handleViewKnowledge(item)}>
                    <Eye className="w-4 h-4 mr-2" />
                    查看
                  </Button>
                  <Button size="sm" variant="outline" onClick={() => handleLike(item.id)}>
                    <Heart className="w-4 h-4" />
                  </Button>
                  <Button size="sm" variant="outline" onClick={() => handleBookmark(item.id)}>
                    <Bookmark className="w-4 h-4" />
                  </Button>
                  <Button size="sm" variant="outline" onClick={() => handleEditKnowledge(item)}>
                    <Edit className="w-4 h-4" />
                  </Button>
                  <Button size="sm" variant="outline" onClick={() => handleDeleteKnowledge(item.id)}>
                    <Trash2 className="w-4 h-4" />
                  </Button>
                </div>
              </Card>
            ))}
          </div>

          {filteredKnowledge.length === 0 && (
            <Card className="p-12 text-center">
              <BookOpen className="w-16 h-16 mx-auto text-gray-400 mb-4" />
              <p className="text-muted-foreground mb-4">暂无知识内容</p>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateKnowledge}>
                <Plus className="w-4 h-4 mr-2" />
                新增知识
              </Button>
            </Card>
          )}
        </TabsContent>

        {/* 分类与标签 */}
        <TabsContent value="category" className="space-y-4">
          {/* 分类说明 */}
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <FolderTree className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-green-900">
                <p className="mb-2">多维度分类与标签体系：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>按作物分类</strong>: 水稻、玉米、小麦、蔬菜等</li>
                  <li>• <strong>按生育期分类</strong>: 播种期、苗期、分蘖期、抽穗期、成熟期等</li>
                  <li>• <strong>按问题类型分类</strong>: 病害、虫害、草害、营养不良等</li>
                  <li>• <strong>按农事类型分类</strong>: 播种、施肥、灌溉、除草、采收等</li>
                  <li>• <strong>支持多级分类</strong>: 主分类下可设置子分类，层级清晰</li>
                  <li>• <strong>灵活标签系统</strong>: 一个知识可添加多个标签，便于交叉检索</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 分类树 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <Layers className="w-5 h-5 text-blue-600" />
                知识分类体系
              </h3>
              <Button size="sm" className="bg-blue-600 hover:bg-blue-700" onClick={handleCreateCategory}>
                <Plus className="w-4 h-4 mr-2" />
                新增分类
              </Button>
            </div>
            <div className="grid grid-cols-2 gap-4">
              {categories.map(category => (
                <Card key={category.id} className="p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-2 flex-1">
                      <span className="text-2xl">{category.icon}</span>
                      <div className="flex-1">
                        <h4>{category.name}</h4>
                        <p className="text-xs text-muted-foreground">
                          {category.count} 篇知识
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-1">
                      <Button size="sm" variant="outline" onClick={() => handleEditCategory(category)}>
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline" 
                        onClick={() => handleDeleteCategory(category.id)}
                        disabled={category.count > 0}
                      >
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>
                  
                  {category.subcategories && (
                    <div className="space-y-2 mt-3 pl-4 border-l-2 border-gray-200">
                      {category.subcategories.map(sub => (
                        <div key={sub.id} className="flex items-center justify-between text-sm">
                          <div className="flex items-center gap-2">
                            <span>{sub.icon}</span>
                            <span>{sub.name}</span>
                          </div>
                          <Badge variant="outline" className="text-xs">
                            {sub.count}
                          </Badge>
                        </div>
                      ))}
                    </div>
                  )}
                </Card>
              ))}
            </div>
          </Card>

          {/* 标签管理 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <Tag className="w-5 h-5 text-purple-600" />
                标签管理
              </h3>
              <Button size="sm" className="bg-purple-600 hover:bg-purple-700" onClick={handleCreateTag}>
                <Plus className="w-4 h-4 mr-2" />
                新增标签
              </Button>
            </div>
            
            {/* 按维度分组展示标签 */}
            {['作物', '生育期', '问题类型', '农事类型'].map(dimension => (
              <div key={dimension} className="mb-6 last:mb-0">
                <h4 className="mb-3 flex items-center gap-2">
                  <Hash className="w-4 h-4 text-muted-foreground" />
                  {dimension}标签
                  <Badge variant="outline" className="ml-2">
                    {tags.filter(tag => tag.category === dimension).length} 个
                  </Badge>
                </h4>
                <div className="flex flex-wrap gap-2">
                  {tags
                    .filter(tag => tag.category === dimension)
                    .map(tag => (
                      <div key={tag.id} className="group relative">
                        <Badge
                          className={`${tag.color} cursor-pointer hover:opacity-80 transition-opacity pr-8`}
                        >
                          <Hash className="w-3 h-3 mr-1" />
                          {tag.name}
                          <span className="ml-2 opacity-70">({tag.count})</span>
                        </Badge>
                        <div className="absolute right-1 top-1/2 -translate-y-1/2 hidden group-hover:flex gap-0.5">
                          <button
                            onClick={() => handleEditTag(tag)}
                            className="p-0.5 hover:bg-black/10 rounded"
                          >
                            <Edit className="w-2.5 h-2.5" />
                          </button>
                          <button
                            onClick={() => handleDeleteTag(tag.id)}
                            className="p-0.5 hover:bg-black/10 rounded"
                            disabled={tag.count > 0}
                          >
                            <Trash2 className="w-2.5 h-2.5" />
                          </button>
                        </div>
                      </div>
                    ))}
                </div>
              </div>
            ))}
          </Card>

          {/* 分类与标签统计 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-green-600" />
                分类统计
              </h3>
              <div className="space-y-3">
                {categories
                  .sort((a, b) => b.count - a.count)
                  .slice(0, 5)
                  .map(cat => (
                    <div key={cat.id} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <span>{cat.icon}</span>
                        <span className="text-sm">{cat.name}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-24 h-2 bg-gray-200 rounded-full overflow-hidden">
                          <div 
                            className="h-full bg-green-500"
                            style={{ width: `${(cat.count / totalKnowledge) * 100}%` }}
                          />
                        </div>
                        <span className="text-sm font-medium w-8 text-right">{cat.count}</span>
                      </div>
                    </div>
                  ))}
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-purple-600" />
                热门标签 TOP10
              </h3>
              <div className="space-y-3">
                {tags
                  .sort((a, b) => b.count - a.count)
                  .slice(0, 10)
                  .map(tag => (
                    <div key={tag.id} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Hash className="w-3 h-3 text-muted-foreground" />
                        <span className="text-sm">{tag.name}</span>
                        <Badge variant="outline" className="text-xs">
                          {tag.category}
                        </Badge>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-16 h-2 bg-gray-200 rounded-full overflow-hidden">
                          <div 
                            className="h-full bg-purple-500"
                            style={{ width: `${(tag.count / totalKnowledge) * 100}%` }}
                          />
                        </div>
                        <span className="text-sm font-medium w-8 text-right">{tag.count}</span>
                      </div>
                    </div>
                  ))}
              </div>
            </Card>
          </div>
        </TabsContent>

        {/* 智能检索 */}
        <TabsContent value="search" className="space-y-4">
          {/* 搜索框 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Search className="w-5 h-5 text-green-600" />
              智能检索
            </h3>
            <div className="flex gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  placeholder="输入关键词搜索知识库..."
                  className="pl-10"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
              <Button className="bg-green-600 hover:bg-green-700">
                <Search className="w-4 h-4 mr-2" />
                搜索
              </Button>
            </div>

            {/* 高级搜索选项 */}
            <div className="mt-4 p-4 bg-gray-50 rounded-lg">
              <h4 className="mb-3 text-sm font-medium">高级搜索</h4>
              <div className="grid grid-cols-4 gap-3">
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择作物" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="水稻">水稻</SelectItem>
                    <SelectItem value="玉米">玉米</SelectItem>
                    <SelectItem value="小麦">小麦</SelectItem>
                  </SelectContent>
                </Select>

                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择生育期" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="播种期">播种期</SelectItem>
                    <SelectItem value="苗期">苗期</SelectItem>
                    <SelectItem value="成熟期">成熟期</SelectItem>
                  </SelectContent>
                </Select>

                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="问题类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="病害">病害</SelectItem>
                    <SelectItem value="虫害">虫害</SelectItem>
                    <SelectItem value="营养不良">营养不良</SelectItem>
                  </SelectContent>
                </Select>

                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="内容类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="图文教程">图文教程</SelectItem>
                    <SelectItem value="视频">视频</SelectItem>
                    <SelectItem value="解决方案">解决方案</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </Card>

          {/* 搜索结果 */}
          <Card className="p-6">
            <h3 className="mb-4">
              搜索结果 ({filteredKnowledge.length} 条)
            </h3>
            <div className="space-y-4">
              {filteredKnowledge.map(item => (
                <Card key={item.id} className="p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-start gap-4">
                    <div className={`p-3 rounded-lg ${getTypeColor(item.type)} flex-shrink-0`}>
                      {getTypeIcon(item.type)}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <h4 className="mb-1">{item.title}</h4>
                          <div className="flex items-center gap-2 text-sm text-muted-foreground">
                            <Badge variant="outline" className="text-xs">
                              {item.category}
                            </Badge>
                            <span>•</span>
                            <span className="flex items-center gap-1">
                              <User className="w-3 h-3" />
                              {item.author}
                            </span>
                            <span>•</span>
                            <span className="flex items-center gap-1">
                              <Calendar className="w-3 h-3" />
                              {item.createdAt}
                            </span>
                          </div>
                        </div>
                        <div className="flex gap-2">
                          <Button size="sm" variant="outline" onClick={() => handleViewKnowledge(item)}>
                            <Eye className="w-4 h-4 mr-1" />
                            查看
                          </Button>
                        </div>
                      </div>
                      <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                        {stripHtmlTags(item.content)}
                      </p>
                      <div className="flex items-center justify-between">
                        <div className="flex flex-wrap gap-1">
                          {item.tags.map(tag => (
                            <Badge key={tag} variant="outline" className="text-xs">
                              {tag}
                            </Badge>
                          ))}
                        </div>
                        <div className="flex items-center gap-3 text-xs text-muted-foreground">
                          <span className="flex items-center gap-1">
                            <Eye className="w-3 h-3" />
                            {item.views}
                          </span>
                          <span className="flex items-center gap-1">
                            <Heart className="w-3 h-3" />
                            {item.likes}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 搜索说明 */}
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Target className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">智能检索功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>全文检索</strong>: 搜索标题、内容、标签等所有文本</li>
                  <li>• <strong>多维筛选</strong>: 支持按作物、生育期、问题类型、内容类型组合筛选</li>
                  <li>• <strong>模糊匹配</strong>: 支持关键词模糊搜索，提高检索准确率</li>
                  <li>• <strong>相关度排序</strong>: 搜索结果按相关度智能排序</li>
                  <li>• <strong>搜索历史</strong>: 记录搜索历史，快速重复查询</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 创建/编辑知识对话框 */}
      <Dialog open={showKnowledgeDialog} onOpenChange={setShowKnowledgeDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{selectedKnowledge ? '编辑知识' : '新增知识'}</DialogTitle>
            <DialogDescription>
              创建或编辑知识库内容，支持多种媒体形式
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>标题 <span className="text-red-500">*</span></label>
                <Input 
                  placeholder="请输入知识标题" 
                  className="mt-2" 
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                />
              </div>
              <div>
                <label>内容类型 <span className="text-red-500">*</span></label>
                <Select value={formData.type} onValueChange={(value: ContentType) => setFormData({ ...formData, type: value })}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择内容类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="文本">📄 结构化文本</SelectItem>
                    <SelectItem value="图文教程">📖 图文教程</SelectItem>
                    <SelectItem value="视频">🎥 专家视频</SelectItem>
                    <SelectItem value="病虫害图谱">🐛 病虫害图谱</SelectItem>
                    <SelectItem value="解决方案">💡 解决方案</SelectItem>
                    <SelectItem value="FAQ">❓ 常见问答(FAQ)</SelectItem>
                    <SelectItem value="文献">📚 外部权威文献</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>分类 <span className="text-red-500">*</span></label>
                <Select value={formData.category} onValueChange={(value) => setFormData({ ...formData, category: value })}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择分类" />
                  </SelectTrigger>
                  <SelectContent>
                    {categories.map(cat => (
                      <SelectItem key={cat.id} value={cat.name}>
                        {cat.icon} {cat.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 标签选择 */}
            <div>
              <label>标签</label>
              <Card className="mt-2 p-3 max-h-64 overflow-y-auto">
                <p className="text-xs text-muted-foreground mb-3">
                  从已维护的标签中选择（可多选）
                </p>
                
                {/* 按维度分组展示标签 */}
                {['作物', '生育期', '问题类型', '农事类型'].map(dimension => {
                  const dimensionTags = tags.filter(tag => tag.category === dimension);
                  if (dimensionTags.length === 0) return null;
                  
                  return (
                    <div key={dimension} className="mb-3 last:mb-0">
                      <h4 className="text-xs mb-2 flex items-center gap-2">
                        <Hash className="w-3 h-3 text-muted-foreground" />
                        {dimension}
                      </h4>
                      <div className="flex flex-wrap gap-2">
                        {dimensionTags.map(tag => (
                          <Badge
                            key={tag.id}
                            className={`cursor-pointer transition-all ${
                              selectedTagIds.includes(tag.id)
                                ? tag.color + ' ring-2 ring-offset-1 ring-green-600'
                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            }`}
                            onClick={() => {
                              if (selectedTagIds.includes(tag.id)) {
                                setSelectedTagIds(selectedTagIds.filter(id => id !== tag.id));
                              } else {
                                setSelectedTagIds([...selectedTagIds, tag.id]);
                              }
                            }}
                          >
                            <Hash className="w-3 h-3 mr-1" />
                            {tag.name}
                            {selectedTagIds.includes(tag.id) && (
                              <span className="ml-1">✓</span>
                            )}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  );
                })}
                
                {tags.length === 0 && (
                  <p className="text-sm text-muted-foreground text-center py-4">
                    暂无可用标签，请先在"分类与标签"页面创建标签
                  </p>
                )}
              </Card>
              {selectedTagIds.length > 0 && (
                <p className="text-xs text-muted-foreground mt-1">
                  已选择 {selectedTagIds.length} 个标签
                </p>
              )}
            </div>

            <div>
              <label>内容 <span className="text-red-500">*</span></label>
              <div className="mt-2">
                <RichTextEditor
                  value={formData.content}
                  onChange={(value) => setFormData({ ...formData, content: value })}
                  placeholder="请输入知识内容..."
                  minHeight="300px"
                />
              </div>
              {/* <Textarea style={{ display: 'none' }}
                placeholder={
                  formData.type === 'FAQ' ? 'Q: 问题描述？\nA: 答案内容...' :
                  formData.type === '解决方案' ? '1. 问题分析\n2. 解决步骤\n3. 预防措施...' :
                  formData.type === '文献' ? '摘要：\n关键词：\n正文内容...' :
                  '请输入知识内容...'
                }
                className="mt-2"
                rows={12}
                value={formData.content}
                onChange={(e) => setFormData({ ...formData, content: e.target.value })}
              /> */}
            </div>

            {/* 媒体上传区域 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <h4 className="mb-3 flex items-center gap-2">
                <ImageIcon className="w-4 h-4 text-blue-600" />
                多媒体内容
              </h4>
              <div className="grid grid-cols-3 gap-3">
                <Button variant="outline" className="w-full">
                  <ImageIcon className="w-4 h-4 mr-2" />
                  上传图片
                </Button>
                <Button variant="outline" className="w-full">
                  <Video className="w-4 h-4 mr-2" />
                  上传视频
                </Button>
                <Button variant="outline" className="w-full">
                  <Upload className="w-4 h-4 mr-2" />
                  上传附件
                </Button>
              </div>
              <p className="text-xs text-muted-foreground mt-2">
                支持上传图片(JPG/PNG)、视频(MP4)、文档(PDF/DOC)等多种格式
              </p>
            </Card>

            {/* 外部链接（用于文献） */}
            {formData.type === '文献' && (
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>外部文献链接</label>
                  <Input 
                    placeholder="https://..." 
                    className="mt-2" 
                    value={formData.externalLink}
                    onChange={(e) => setFormData({ ...formData, externalLink: e.target.value })}
                  />
                </div>
                <div>
                  <label>文献来源</label>
                  <Input 
                    placeholder="如：农业科学院、农业部官网" 
                    className="mt-2" 
                    value={formData.reference}
                    onChange={(e) => setFormData({ ...formData, reference: e.target.value })}
                  />
                </div>
              </div>
            )}

            {/* 元数据 */}
            <Card className="p-4 bg-gray-50">
              <h4 className="mb-3 flex items-center gap-2">
                <Database className="w-4 h-4 text-gray-600" />
                元数据（便于精准检索）
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>作物</label>
                  <Input 
                    placeholder="如：水稻" 
                    className="mt-2" 
                    value={formData.crop}
                    onChange={(e) => setFormData({ ...formData, crop: e.target.value })}
                  />
                </div>
                <div>
                  <label>生育期</label>
                  <Input 
                    placeholder="如：分蘖期" 
                    className="mt-2" 
                    value={formData.growthStage}
                    onChange={(e) => setFormData({ ...formData, growthStage: e.target.value })}
                  />
                </div>
                <div>
                  <label>农事类型</label>
                  <Input 
                    placeholder="如：播种、施肥、灌溉" 
                    className="mt-2" 
                    value={formData.operationType}
                    onChange={(e) => setFormData({ ...formData, operationType: e.target.value })}
                  />
                </div>
                <div>
                  <label>问题类型</label>
                  <Input 
                    placeholder="如：病害、虫害" 
                    className="mt-2" 
                    value={formData.problemType}
                    onChange={(e) => setFormData({ ...formData, problemType: e.target.value })}
                  />
                </div>
                <div>
                  <label>难度级别</label>
                  <Select value={formData.difficulty} onValueChange={(value) => setFormData({ ...formData, difficulty: value })}>
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择难度" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="简单">🟢 简单 - 农户可自行操作</SelectItem>
                      <SelectItem value="中等">🟡 中等 - 需要一定经验</SelectItem>
                      <SelectItem value="较难">🟠 较难 - 需要专业指导</SelectItem>
                      <SelectItem value="专业">🔴 专业 - 专家级别</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </Card>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowKnowledgeDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveKnowledge}>
                <Upload className="w-4 h-4 mr-2" />
                保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 分类管理对话框 */}
      <Dialog open={showCategoryDialog} onOpenChange={setShowCategoryDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{editingCategory ? '编辑分类' : '新增分类'}</DialogTitle>
            <DialogDescription>
              设置知识分类的名称、图标和颜色
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label>分类名称 <span className="text-red-500">*</span></label>
              <Input
                placeholder="如：种植技术"
                className="mt-2"
                value={categoryFormData.name}
                onChange={(e) => setCategoryFormData({ ...categoryFormData, name: e.target.value })}
              />
            </div>

            <div>
              <label>图标 Emoji <span className="text-red-500">*</span></label>
              <Input
                placeholder="如：🌱"
                className="mt-2"
                value={categoryFormData.icon}
                onChange={(e) => setCategoryFormData({ ...categoryFormData, icon: e.target.value })}
              />
              <p className="text-xs text-muted-foreground mt-1">
                输入一个 Emoji 表情作为图标
              </p>
            </div>

            <div>
              <label>颜色样式</label>
              <Select 
                value={categoryFormData.color} 
                onValueChange={(value) => setCategoryFormData({ ...categoryFormData, color: value })}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="bg-blue-100 text-blue-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-blue-100" />
                      蓝色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-green-100 text-green-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-green-100" />
                      绿色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-red-100 text-red-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-red-100" />
                      红色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-yellow-100 text-yellow-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-yellow-100" />
                      黄色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-purple-100 text-purple-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-purple-100" />
                      紫色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-gray-100 text-gray-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-gray-100" />
                      灰色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-orange-100 text-orange-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-orange-100" />
                      橙色
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 预览 */}
            <Card className="p-4 bg-gray-50">
              <p className="text-xs text-muted-foreground mb-2">预览效果：</p>
              <div className="flex items-center gap-2">
                <span className="text-2xl">{categoryFormData.icon || '❓'}</span>
                <Badge className={categoryFormData.color}>
                  {categoryFormData.name || '分类名称'}
                </Badge>
              </div>
            </Card>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowCategoryDialog(false)}>
                取消
              </Button>
              <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleSaveCategory}>
                保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 标签管理对话框 */}
      <Dialog open={showTagDialog} onOpenChange={setShowTagDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{editingTag ? '编辑标签' : '新增标签'}</DialogTitle>
            <DialogDescription>
              设置标签的名称、维度分类和颜色
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label>标签名称 <span className="text-red-500">*</span></label>
              <Input
                placeholder="如：水稻"
                className="mt-2"
                value={tagFormData.name}
                onChange={(e) => setTagFormData({ ...tagFormData, name: e.target.value })}
              />
            </div>

            <div>
              <label>标签维度 <span className="text-red-500">*</span></label>
              <Select 
                value={tagFormData.category} 
                onValueChange={(value) => setTagFormData({ ...tagFormData, category: value })}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="作物">
                    <div className="flex items-center gap-2">
                      <Leaf className="w-4 h-4" />
                      作物
                    </div>
                  </SelectItem>
                  <SelectItem value="生育期">
                    <div className="flex items-center gap-2">
                      <Calendar className="w-4 h-4" />
                      生育期
                    </div>
                  </SelectItem>
                  <SelectItem value="问题类型">
                    <div className="flex items-center gap-2">
                      <AlertCircle className="w-4 h-4" />
                      问题类型
                    </div>
                  </SelectItem>
                  <SelectItem value="农事类型">
                    <div className="flex items-center gap-2">
                      <Sprout className="w-4 h-4" />
                      农事类型
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <label>颜色样式</label>
              <Select 
                value={tagFormData.color} 
                onValueChange={(value) => setTagFormData({ ...tagFormData, color: value })}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="bg-green-100 text-green-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-green-100" />
                      绿色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-blue-100 text-blue-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-blue-100" />
                      蓝色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-purple-100 text-purple-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-purple-100" />
                      紫色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-red-100 text-red-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-red-100" />
                      红色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-yellow-100 text-yellow-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-yellow-100" />
                      黄色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-orange-100 text-orange-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-orange-100" />
                      橙色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-cyan-100 text-cyan-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-cyan-100" />
                      青色
                    </div>
                  </SelectItem>
                  <SelectItem value="bg-pink-100 text-pink-800">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded bg-pink-100" />
                      粉色
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 预览 */}
            <Card className="p-4 bg-gray-50">
              <p className="text-xs text-muted-foreground mb-2">预览效果：</p>
              <Badge className={tagFormData.color}>
                <Hash className="w-3 h-3 mr-1" />
                {tagFormData.name || '标签名称'}
              </Badge>
            </Card>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowTagDialog(false)}>
                取消
              </Button>
              <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSaveTag}>
                保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 查看知识详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-3">
              <div className={`p-2 rounded-lg ${getTypeColor(viewingKnowledge?.type || '文本')}`}>
                {getTypeIcon(viewingKnowledge?.type || '文本')}
              </div>
              {viewingKnowledge?.title}
            </DialogTitle>
            <DialogDescription>
              {viewingKnowledge?.category} | 作者：{viewingKnowledge?.author} | 发布于：{viewingKnowledge?.createdAt}
            </DialogDescription>
          </DialogHeader>

          {viewingKnowledge && (
            <div className="space-y-6">
              {/* 标签 */}
              <div className="flex flex-wrap gap-2">
                {viewingKnowledge.tags.map(tag => (
                  <Badge key={tag} variant="outline">
                    <Hash className="w-3 h-3 mr-1" />
                    {tag}
                  </Badge>
                ))}
              </div>

              {/* 内容 */}
              <Card className="p-6 bg-gray-50">
                <div 
                  className="prose max-w-none"
                  dangerouslySetInnerHTML={{ __html: viewingKnowledge.content || '' }}
                />
              </Card>

              {/* 媒体内容 */}
              {viewingKnowledge.media && (
                <div className="space-y-4">
                  {viewingKnowledge.media.images && viewingKnowledge.media.images.length > 0 && (
                    <Card className="p-4">
                      <h4 className="mb-3 flex items-center gap-2">
                        <ImageIcon className="w-4 h-4 text-blue-600" />
                        图片资料 ({viewingKnowledge.media.images.length})
                      </h4>
                      <div className="grid grid-cols-4 gap-3">
                        {viewingKnowledge.media.images.map((img, idx) => (
                          <div key={idx} className="aspect-square bg-gray-200 rounded-lg flex items-center justify-center">
                            <ImageIcon className="w-8 h-8 text-gray-400" />
                          </div>
                        ))}
                      </div>
                    </Card>
                  )}

                  {viewingKnowledge.media.videos && viewingKnowledge.media.videos.length > 0 && (
                    <Card className="p-4">
                      <h4 className="mb-3 flex items-center gap-2">
                        <Video className="w-4 h-4 text-purple-600" />
                        视频教程 ({viewingKnowledge.media.videos.length})
                      </h4>
                      <div className="aspect-video bg-gray-200 rounded-lg flex items-center justify-center">
                        <Video className="w-16 h-16 text-gray-400" />
                      </div>
                    </Card>
                  )}

                  {viewingKnowledge.media.attachments && viewingKnowledge.media.attachments.length > 0 && (
                    <Card className="p-4">
                      <h4 className="mb-3 flex items-center gap-2">
                        <Link2 className="w-4 h-4 text-gray-600" />
                        附件下载 ({viewingKnowledge.media.attachments.length})
                      </h4>
                      <div className="space-y-2">
                        {viewingKnowledge.media.attachments.map((file, idx) => (
                          <div key={idx} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                            <div className="flex items-center gap-2">
                              <FileText className="w-4 h-4 text-blue-600" />
                              <span className="text-sm">{file.name}</span>
                            </div>
                            <Button size="sm" variant="outline">
                              <Download className="w-3 h-3 mr-1" />
                              下载
                            </Button>
                          </div>
                        ))}
                      </div>
                    </Card>
                  )}
                </div>
              )}

              {/* 元数据 */}
              <Card className="p-4 bg-blue-50">
                <h4 className="mb-3">知识元数据</h4>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  {viewingKnowledge.metadata.crop && (
                    <div>
                      <span className="text-muted-foreground">作物：</span>
                      <span className="font-medium">{viewingKnowledge.metadata.crop}</span>
                    </div>
                  )}
                  {viewingKnowledge.metadata.growthStage && (
                    <div>
                      <span className="text-muted-foreground">生育期：</span>
                      <span className="font-medium">{viewingKnowledge.metadata.growthStage}</span>
                    </div>
                  )}
                  {viewingKnowledge.metadata.operationType && (
                    <div>
                      <span className="text-muted-foreground">农事类型：</span>
                      <span className="font-medium">{viewingKnowledge.metadata.operationType}</span>
                    </div>
                  )}
                  {viewingKnowledge.metadata.problemType && (
                    <div>
                      <span className="text-muted-foreground">问题类型：</span>
                      <span className="font-medium">{viewingKnowledge.metadata.problemType}</span>
                    </div>
                  )}
                  {viewingKnowledge.metadata.difficulty && (
                    <div>
                      <span className="text-muted-foreground">难度：</span>
                      <span className="font-medium">{viewingKnowledge.metadata.difficulty}</span>
                    </div>
                  )}
                </div>
              </Card>

              {/* 互动区域 */}
              <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                <div className="flex items-center gap-6 text-sm text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <Eye className="w-4 h-4" />
                    浏览 {viewingKnowledge.views}
                  </span>
                  <span className="flex items-center gap-1">
                    <Heart className="w-4 h-4" />
                    点赞 {viewingKnowledge.likes}
                  </span>
                  <span className="flex items-center gap-1">
                    <Bookmark className="w-4 h-4" />
                    收藏 {viewingKnowledge.bookmarks}
                  </span>
                  <span className="flex items-center gap-1">
                    <MessageSquare className="w-4 h-4" />
                    评论 0
                  </span>
                </div>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => handleLike(viewingKnowledge.id)}>
                    <Heart className="w-4 h-4 mr-1" />
                    点赞
                  </Button>
                  <Button size="sm" variant="outline" onClick={() => handleBookmark(viewingKnowledge.id)}>
                    <Bookmark className="w-4 h-4 mr-1" />
                    收藏
                  </Button>
                  <Button size="sm" variant="outline">
                    <Share2 className="w-4 h-4 mr-1" />
                    分享
                  </Button>
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
