import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { 
  TrendingUp, 
  TrendingDown, 
  Minus, 
  Search, 
  RefreshCw,
  Star,
  Eye,
  Heart,
  MessageCircle,
  Share2,
  Loader2
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

export default function HotTopics() {
  const [topics, setTopics] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [selectedTopics, setSelectedTopics] = useState([]);

  useEffect(() => {
    loadTopics();
  }, []);

  const loadTopics = async () => {
    setLoading(true);
    try {
      // 模拟数据加载
      const mockTopics = [
        {
          id: '1',
          title: '夏季穿搭新趋势',
          platform: 'xiaohongshu',
          heat_score: 95,
          keyword: '夏季穿搭',
          content: '今年夏季穿搭新趋势，简约风格大受欢迎，清爽配色成为主流',
          trend_direction: 'up',
          category: '时尚',
          created_date: '2024-01-15T10:00:00Z',
          views: 125000,
          likes: 8500,
          comments: 1200,
          shares: 450
        },
        {
          id: '2',
          title: 'AI换脸技术应用',
          platform: 'douyin',
          heat_score: 88,
          keyword: 'AI换脸',
          content: 'AI换脸技术在短视频创作中的应用，提升内容创作效率',
          trend_direction: 'up',
          category: '科技',
          created_date: '2024-01-15T09:30:00Z',
          views: 98000,
          likes: 7200,
          comments: 950,
          shares: 320
        },
        {
          id: '3',
          title: '美妆产品测评',
          platform: 'weibo',
          heat_score: 82,
          keyword: '美妆测评',
          content: '最新美妆产品测评，真实使用体验分享',
          trend_direction: 'stable',
          category: '美妆',
          created_date: '2024-01-15T08:45:00Z',
          views: 75000,
          likes: 5800,
          comments: 780,
          shares: 280
        },
        {
          id: '4',
          title: '生活方式分享',
          platform: 'bilibili',
          heat_score: 75,
          keyword: '生活方式',
          content: '年轻人生活方式分享，追求品质生活的新理念',
          trend_direction: 'down',
          category: '生活',
          created_date: '2024-01-15T07:20:00Z',
          views: 65000,
          likes: 4200,
          comments: 650,
          shares: 180
        }
      ];
      setTopics(mockTopics);
    } catch (error) {
      console.error('加载热点失败:', error);
    }
    setLoading(false);
  };

  const fetchLatestTopics = async () => {
    setLoading(true);
    try {
      // 模拟获取最新热点
      const newTopics = [
        {
          id: Date.now().toString(),
          title: '新热点话题示例',
          platform: 'xiaohongshu',
          heat_score: 90,
          keyword: '新热点',
          content: '这是一个新获取的热点话题示例',
          trend_direction: 'up',
          category: '时尚',
          created_date: new Date().toISOString(),
          views: 100000,
          likes: 8000,
          comments: 1000,
          shares: 400
        }
      ];
      
      setTopics(prev => [...newTopics, ...prev]);
    } catch (error) {
      console.error('获取热点失败:', error);
    }
    setLoading(false);
  };

  const toggleTopicSelection = (topicId) => {
    setSelectedTopics(prev => 
      prev.includes(topicId) 
        ? prev.filter(id => id !== topicId)
        : [...prev, topicId]
    );
  };

  const getTrendIcon = (direction) => {
    switch (direction) {
      case 'up':
        return <TrendingUp className="w-4 h-4 text-green-600" />;
      case 'down':
        return <TrendingDown className="w-4 h-4 text-red-600" />;
      default:
        return <Minus className="w-4 h-4 text-gray-600" />;
    }
  };

  const getPlatformColor = (platform) => {
    const colors = {
      xiaohongshu: 'bg-red-100 text-red-700',
      douyin: 'bg-blue-100 text-blue-700',
      weibo: 'bg-orange-100 text-orange-700',
      bilibili: 'bg-pink-100 text-pink-700'
    };
    return colors[platform] || 'bg-gray-100 text-gray-700';
  };

  const getPlatformName = (platform) => {
    const names = {
      xiaohongshu: '小红书',
      douyin: '抖音',
      weibo: '微博',
      bilibili: 'B站'
    };
    return names[platform] || platform;
  };

  const filteredTopics = topics.filter(topic => {
    const matchesSearch = topic.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         topic.keyword.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesTab = activeTab === 'all' || topic.category === activeTab;
    return matchesSearch && matchesTab;
  });

  const categories = [
    { value: 'all', label: '全部分类' },
    { value: '时尚', label: '时尚' },
    { value: '美妆', label: '美妆' },
    { value: '科技', label: '科技' },
    { value: '生活', label: '生活' },
    { value: '娱乐', label: '娱乐' }
  ];

  return (
    <div className="p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-slate-900 mb-2">平台热点</h1>
          <p className="text-slate-600">实时监控各平台热点话题，把握营销趋势</p>
        </div>

        {/* 操作工具栏 */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mb-6">
          <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
            <div className="flex flex-1 gap-4">
              {/* 搜索框 */}
              <div className="relative flex-1 max-w-md">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
                <Input
                  placeholder="搜索热点话题..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>

              {/* 分类筛选 */}
              <div className="flex gap-2">
                {categories.map(category => (
                  <Button
                    key={category.value}
                    variant={activeTab === category.value ? "default" : "outline"}
                    size="sm"
                    onClick={() => setActiveTab(category.value)}
                  >
                    {category.label}
                  </Button>
                ))}
              </div>
            </div>

            {/* 刷新按钮 */}
            <Button onClick={fetchLatestTopics} disabled={loading}>
              {loading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  获取中...
                </>
              ) : (
                <>
                  <RefreshCw className="w-4 h-4 mr-2" />
                  获取最新热点
                </>
              )}
            </Button>
          </div>
        </div>

        {/* 统计信息 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">总热点</p>
                  <p className="text-2xl font-bold text-slate-900">{topics.length}</p>
                </div>
                <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                  <TrendingUp className="w-5 h-5 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">上升趋势</p>
                  <p className="text-2xl font-bold text-slate-900">
                    {topics.filter(t => t.trend_direction === 'up').length}
                  </p>
                </div>
                <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                  <TrendingUp className="w-5 h-5 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">平均热度</p>
                  <p className="text-2xl font-bold text-slate-900">
                    {Math.round(topics.reduce((sum, t) => sum + t.heat_score, 0) / topics.length)}
                  </p>
                </div>
                <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
                  <Star className="w-5 h-5 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">已选择</p>
                  <p className="text-2xl font-bold text-slate-900">{selectedTopics.length}</p>
                </div>
                <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Heart className="w-5 h-5 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 热点列表 */}
        <div className="grid gap-6">
          {loading && topics.length === 0 ? (
            <div className="text-center py-12">
              <Loader2 className="w-8 h-8 animate-spin text-blue-600 mx-auto mb-4" />
              <p className="text-slate-600">加载中...</p>
            </div>
          ) : (
            <AnimatePresence>
              {filteredTopics.map((topic) => (
                <motion.div
                  key={topic.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  transition={{ duration: 0.3 }}
                >
                  <Card className="hover:shadow-md transition-shadow">
                    <CardContent className="p-6">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-3 mb-3">
                            <Badge className={getPlatformColor(topic.platform)}>
                              {getPlatformName(topic.platform)}
                            </Badge>
                            <Badge variant="outline">{topic.category}</Badge>
                            <div className="flex items-center gap-1">
                              {getTrendIcon(topic.trend_direction)}
                              <span className="text-sm text-slate-600">
                                {topic.trend_direction === 'up' ? '上升' : 
                                 topic.trend_direction === 'down' ? '下降' : '稳定'}
                              </span>
                            </div>
                          </div>
                          
                          <h3 className="text-lg font-semibold text-slate-900 mb-2">
                            {topic.title}
                          </h3>
                          
                          <p className="text-slate-600 mb-4">{topic.content}</p>
                          
                          <div className="flex items-center gap-6 text-sm text-slate-500">
                            <div className="flex items-center gap-1">
                              <Eye className="w-4 h-4" />
                              <span>{topic.views.toLocaleString()}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <Heart className="w-4 h-4" />
                              <span>{topic.likes.toLocaleString()}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <MessageCircle className="w-4 h-4" />
                              <span>{topic.comments.toLocaleString()}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <Share2 className="w-4 h-4" />
                              <span>{topic.shares.toLocaleString()}</span>
                            </div>
                          </div>
                        </div>
                        
                        <div className="flex flex-col items-end gap-3">
                          <div className="text-right">
                            <div className="text-2xl font-bold text-slate-900">
                              {topic.heat_score}
                            </div>
                            <div className="text-sm text-slate-500">热度评分</div>
                          </div>
                          
                          <Button
                            variant={selectedTopics.includes(topic.id) ? "default" : "outline"}
                            size="sm"
                            onClick={() => toggleTopicSelection(topic.id)}
                          >
                            {selectedTopics.includes(topic.id) ? '已选择' : '选择'}
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </AnimatePresence>
          )}

          {!loading && filteredTopics.length === 0 && (
            <Card>
              <CardContent className="p-12 text-center">
                <Search className="w-12 h-12 text-slate-400 mx-auto mb-4" />
                <p className="text-slate-600">未找到匹配的热点话题</p>
                <p className="text-sm text-slate-500 mt-1">尝试调整搜索条件或获取最新热点</p>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}