import { useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Calendar,
  Eye,
  ArrowRight,
  Clock,
  TrendingUp,
  Tag,
  Play,
  Pause,
  Volume2,
  VolumeX,
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import { formatDate } from '../lib/utils';
import { NEWS_CATEGORIES } from '../lib/constants';
import { usePageTitle } from '../hooks/usePageTitle';

// 模拟新闻数据
const allNews = [
  {
    id: 1,
    title: '示例集团荣获"2025年度优秀企业"称号',
    excerpt: '在近日举办的年度企业评选活动中，示例集团凭借其卓越的经营业绩和社会责任表现，荣获"2025年度优秀企业"称号。这一荣誉是对示例集团多年来坚持创新发展的肯定。',
    category: 'company',
    date: '2025-12-20',
    readCount: 1256,
    image: null,
    isHot: true,
  },
  {
    id: 2,
    title: '金融科技创新论坛圆满落幕，示例集团分享行业洞察',
    excerpt: '示例集团受邀参加金融科技创新论坛，与行业专家共同探讨金融科技发展趋势，分享公司在数字化转型方面的实践经验。与会嘉宾对示例集团的创新成果给予了高度评价。',
    category: 'industry',
    date: '2025-12-15',
    readCount: 892,
    image: null,
    isHot: true,
  },
  {
    id: 3,
    title: '示例集团完成新一轮战略融资，估值突破百亿',
    excerpt: '示例集团宣布完成新一轮战略融资，本轮融资由知名投资机构领投，估值突破百亿元人民币，标志着公司发展进入新阶段。此轮融资将用于加大技术研发和市场拓展力度。',
    category: 'company',
    date: '2025-12-10',
    readCount: 2341,
    image: null,
    isHot: true,
  },
  {
    id: 4,
    title: '示例集团发布2025年度社会责任报告',
    excerpt: '示例集团正式发布《2025年度社会责任报告》，全面展示了公司在环境保护、社会公益、公司治理等方面的实践成果。报告显示，示例集团在ESG领域取得了显著进步。',
    category: 'company',
    date: '2025-12-05',
    readCount: 567,
    image: null,
    isHot: false,
  },
  {
    id: 5,
    title: '人工智能赋能金融服务行业论坛成功举办',
    excerpt: '由示例集团主办的人工智能赋能金融服务行业论坛在北京成功举办。来自金融机构、科技公司、学术机构的专家学者共同探讨AI技术在金融服务领域的应用前景。',
    category: 'industry',
    date: '2025-11-28',
    readCount: 743,
    image: null,
    isHot: false,
  },
  {
    id: 6,
    title: '示例集团获得国家级高新技术企业认证',
    excerpt: '示例集团正式获得国家级高新技术企业认证，这标志着集团在技术创新和研发投入方面获得了国家层面的认可。示例集团将继续加大研发投入，提升自主创新能力。',
    category: 'achievement',
    date: '2025-11-20',
    readCount: 1089,
    image: null,
    isHot: true,
  },
  {
    id: 7,
    title: '示例集团与清华大学签署战略合作协议',
    excerpt: '示例集团与清华大学正式签署战略合作协议，双方将在人才培养、技术研发、成果转化等方面开展深度合作。这一合作将为示例集团的创新发展提供强大的智力支持。',
    category: 'company',
    date: '2025-11-15',
    readCount: 621,
    image: null,
    isHot: false,
  },
  {
    id: 8,
    title: '数字化转型趋势报告发布，示例集团引领行业发展',
    excerpt: '示例集团研究院发布《2025企业数字化转型趋势报告》，深入分析了当前数字化转型的发展态势和未来趋势。报告指出，数字化转型已成为企业提升竞争力的关键路径。',
    category: 'industry',
    date: '2025-11-08',
    readCount: 456,
    image: null,
    isHot: false,
  },
  {
    id: 9,
    title: '示例集团获评"最佳雇主品牌"荣誉称号',
    excerpt: '在2025年度人力资源管理峰会上，示例集团凭借其在人才培养、员工发展、企业文化等方面的卓越表现，荣获"最佳雇主品牌"荣誉称号。这一荣誉体现了员工对示例集团的高度认可。',
    category: 'achievement',
    date: '2025-11-01',
    readCount: 389,
    image: null,
    isHot: false,
  },
  {
    id: 10,
    title: '示例集团启动"绿色金融"专项计划',
    excerpt: '示例集团正式宣布启动"绿色金融"专项计划，计划在未来三年内投入100亿元支持绿色产业发展。这一计划的推出，体现了示例集团积极践行可持续发展理念的决心。',
    category: 'company',
    date: '2025-10-25',
    readCount: 723,
    image: null,
    isHot: false,
  },
  {
    id: 11,
    title: '产业投资基金发展趋势研讨会在京举行',
    excerpt: '由示例集团主办的产业投资基金发展趋势研讨会在北京举行。来自监管部门、投资机构、产业龙头企业的代表就产业投资基金的发展方向和投资策略进行了深入探讨。',
    category: 'industry',
    date: '2025-10-18',
    readCount: 312,
    image: null,
    isHot: false,
  },
  {
    id: 12,
    title: '示例集团入选"北京民营企业百强"榜单',
    excerpt: '北京市工商联发布2025年度北京民营企业百强榜单，示例集团凭借优异的经营业绩和创新能力，成功入选该榜单。这一荣誉是对示例集团综合实力的又一次肯定。',
    category: 'achievement',
    date: '2025-10-10',
    readCount: 567,
    image: null,
    isHot: false,
  },
];

// 新闻分类映射
const categoryMap: Record<string, { label: string; color: string }> = {
  all: { label: '全部', color: 'bg-primary text-white' },
  company: { label: '公司动态', color: 'bg-primary/10 text-primary' },
  industry: { label: '行业资讯', color: 'bg-accent/20 text-accent-dark' },
  achievement: { label: '荣誉资质', color: 'bg-green-100 text-green-700' },
};

// 每页新闻数量
const ITEMS_PER_PAGE = 6;

/**
 * 新闻卡片组件
 */
const NewsCard: React.FC<{ news: typeof allNews[0]; index: number }> = ({
  news,
  index,
}) => {
  const category = categoryMap[news.category] || categoryMap.company;

  return (
    <motion.article
      className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-lg transition-all duration-300 group"
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      transition={{ delay: index * 0.05, duration: 0.4 }}
      whileHover={{ y: -5 }}
    >
      {/* 图片区域 */}
      <Link to={`/news/${news.id}`} className="block aspect-[16/9] relative overflow-hidden">
        <img 
          src={`https://images.unsplash.com/photo-${
            news.category === 'company' ? '1560179707-f14e90ef3623' : 
            news.category === 'industry' ? '1504868584819-f8e8b4b6d7e3' : 
            '1552664730-d307ca884978'
          }?w=800&h=450&fit=crop&auto=format&q=80`}
          alt={news.title}
          className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent" />
        {/* 分类标签 */}
        <span className={`absolute top-4 left-4 px-3 py-1 text-xs font-medium rounded-full backdrop-blur-sm ${category.color}`}>
          {category.label}
        </span>
        {/* 热门标签 */}
        {news.isHot && (
          <span className="absolute top-4 right-4 px-3 py-1 text-xs font-medium bg-red-500 text-white rounded-full flex items-center gap-1 backdrop-blur-sm">
            <TrendingUp size={12} />
            热门
          </span>
        )}
      </Link>

      {/* 内容区域 */}
      <div className="p-6">
        {/* 元信息 */}
        <div className="flex items-center gap-4 text-sm text-gray-500 mb-3">
          <div className="flex items-center gap-1">
            <Calendar size={14} />
            <time dateTime={news.date}>{formatDate(news.date, 'YYYY年MM月DD日')}</time>
          </div>
          <div className="flex items-center gap-1">
            <Eye size={14} />
            <span>{news.readCount}</span>
          </div>
        </div>

        {/* 标题 */}
        <Link to={`/news/${news.id}`}>
          <h3 className="text-lg font-semibold text-primary-dark mb-3 line-clamp-2 group-hover:text-primary transition-colors">
            {news.title}
          </h3>
        </Link>

        {/* 摘要 */}
        <p className="text-gray-600 text-sm leading-relaxed line-clamp-2 mb-4">
          {news.excerpt}
        </p>

        {/* 阅读更多 */}
        <Link
          to={`/news/${news.id}`}
          className="inline-flex items-center gap-2 text-sm font-medium text-primary group-hover:text-primary-light transition-colors"
        >
          阅读全文
          <motion.span
            initial={{ x: 0 }}
            whileHover={{ x: 5 }}
            transition={{ duration: 0.2 }}
          >
            <ArrowRight size={16} />
          </motion.span>
        </Link>
      </div>
    </motion.article>
  );
};

/**
 * 侧边栏热门新闻组件
 */
const HotNewsWidget: React.FC<{ news: typeof allNews[0]; rank: number }> = ({
  news,
  rank,
}) => (
  <Link
    to={`/news/${news.id}`}
    className="flex items-start gap-4 p-4 bg-background rounded-xl hover:bg-white hover:shadow-sm transition-all group"
  >
    <span className="flex-shrink-0 w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center text-primary font-bold text-sm">
      {rank}
    </span>
    <div className="flex-1 min-w-0">
      <h4 className="text-sm font-medium text-primary-dark mb-1 line-clamp-2 group-hover:text-primary transition-colors">
        {news.title}
      </h4>
      <div className="flex items-center gap-2 text-xs text-gray-500">
        <span>{formatDate(news.date, 'YYYY-MM-DD')}</span>
        <span>·</span>
        <span>{news.readCount} 阅读</span>
      </div>
    </div>
  </Link>
);

/**
 * 分页组件
 */
const Pagination: React.FC<{
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
}> = ({ currentPage, totalPages, onPageChange }) => {
  return (
    <div className="flex items-center justify-center gap-2 mt-12">
      {/* 上一页按钮 */}
      <motion.button
        onClick={() => onPageChange(currentPage - 1)}
        disabled={currentPage === 1}
        className="px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        whileHover={{ scale: 1.02 }}
        whileTap={{ scale: 0.98 }}
      >
        上一页
      </motion.button>

      {/* 页码 */}
      {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
        <motion.button
          key={page}
          onClick={() => onPageChange(page)}
          className={`w-10 h-10 text-sm font-medium rounded-lg transition-colors ${
            currentPage === page
              ? 'bg-primary text-white'
              : 'text-gray-600 bg-white border border-gray-200 hover:bg-gray-50'
          }`}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          {page}
        </motion.button>
      ))}

      {/* 下一页按钮 */}
      <motion.button
        onClick={() => onPageChange(currentPage + 1)}
        disabled={currentPage === totalPages}
        className="px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        whileHover={{ scale: 1.02 }}
        whileTap={{ scale: 0.98 }}
      >
        下一页
      </motion.button>
    </div>
  );
};

/**
 * 数字人视频播放器组件
 */
const DigitalHumanVideo: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(true);

  const togglePlay = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const toggleMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  return (
    <motion.div
      className="bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden mb-12"
      initial={{ opacity: 0, y: 30 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.6, delay: 0.2 }}
    >
      <div className="grid lg:grid-cols-5 gap-6">
        {/* 视频播放器 */}
        <div className="lg:col-span-3 relative bg-gradient-to-br from-primary/5 to-primary-light/10">
          <div className="aspect-video relative">
            <video
              ref={videoRef}
              className="w-full h-full object-cover"
              muted={isMuted}
              loop
              playsInline
              poster="https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=1200&h=675&fit=crop"
            >
              <source
                src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
                type="video/mp4"
              />
              您的浏览器不支持视频播放
            </video>

            {/* 播放控制按钮 */}
            <div className="absolute inset-0 flex items-center justify-center bg-black/20 hover:bg-black/30 transition-colors group">
              <motion.button
                onClick={togglePlay}
                className="w-16 h-16 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center text-primary shadow-lg group-hover:scale-110 transition-transform"
                whileHover={{ scale: 1.15 }}
                whileTap={{ scale: 0.95 }}
              >
                {isPlaying ? <Pause size={28} /> : <Play size={28} className="ml-1" />}
              </motion.button>
            </div>

            {/* 音量控制 */}
            <div className="absolute bottom-4 right-4">
              <motion.button
                onClick={toggleMute}
                className="w-10 h-10 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center text-primary shadow-lg"
                whileHover={{ scale: 1.1 }}
                whileTap={{ scale: 0.95 }}
              >
                {isMuted ? <VolumeX size={20} /> : <Volume2 size={20} />}
              </motion.button>
            </div>

            {/* 直播标签 */}
            <div className="absolute top-4 left-4">
              <span className="px-3 py-1 bg-red-500 text-white text-xs font-medium rounded-full flex items-center gap-2">
                <span className="w-2 h-2 bg-white rounded-full animate-pulse" />
                数字人播报
              </span>
            </div>
          </div>
        </div>

        {/* 视频信息 */}
        <div className="lg:col-span-2 p-6 flex flex-col justify-center">
          <div className="mb-4">
            <span className="inline-block px-3 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full mb-3">
              AI 数字人
            </span>
            <h3 className="text-2xl font-bold text-primary-dark mb-3">
              示例集团新闻播报
            </h3>
            <p className="text-gray-600 leading-relaxed mb-4">
              欢迎收看示例集团最新资讯播报。我们使用先进的AI数字人技术，为您带来最新的企业动态、行业资讯和重要公告。
            </p>
          </div>

          <div className="space-y-3 text-sm text-gray-600">
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-primary rounded-full" />
              <span>24小时不间断播报</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-primary rounded-full" />
              <span>实时更新企业资讯</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-primary rounded-full" />
              <span>多语言智能播报</span>
            </div>
          </div>

          <motion.button
            className="mt-6 px-6 py-3 bg-primary text-white rounded-lg font-medium hover:bg-primary-light transition-colors flex items-center justify-center gap-2"
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
          >
            <Play size={18} />
            了解更多
          </motion.button>
        </div>
      </div>
    </motion.div>
  );
};

/**
 * News 组件 - 新闻资讯页面
 */
export const News: React.FC = () => {
  usePageTitle('新闻资讯');
  const [activeCategory, setActiveCategory] = useState('all');
  const [currentPage, setCurrentPage] = useState(1);

  // 根据分类筛选新闻
  const filteredNews =
    activeCategory === 'all'
      ? allNews
      : allNews.filter((news) => news.category === activeCategory);

  // 计算分页
  const totalPages = Math.ceil(filteredNews.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const currentNews = filteredNews.slice(startIndex, startIndex + ITEMS_PER_PAGE);

  // 获取热门新闻 TOP 5
  const hotNews = allNews
    .filter((news) => news.isHot)
    .sort((a, b) => b.readCount - a.readCount)
    .slice(0, 5);

  // 切换分类时重置分页
  const handleCategoryChange = (category: string) => {
    setActiveCategory(category);
    setCurrentPage(1);
  };

  return (
    <motion.div
      className="min-h-screen bg-background"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
    >
      {/* 顶部导航 */}
      <Header />

      {/* 主内容 */}
      <main>
        {/* 页面标题 */}
        <section className="pt-32 pb-16 bg-gradient-to-br from-primary to-primary-light">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <motion.div
              className="text-center text-white"
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <h1 className="text-4xl md:text-5xl font-bold mb-4">
                新闻资讯
              </h1>
              <p className="text-xl text-white/80 max-w-3xl mx-auto">
                了解示例集团最新动态和行业资讯
              </p>
            </motion.div>
          </div>
        </section>

        {/* 新闻内容区域 */}
        <section className="py-12">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            {/* 数字人视频播放器 */}
            <DigitalHumanVideo />

            <div className="grid lg:grid-cols-3 gap-8">
              {/* 左侧新闻列表 */}
              <div className="lg:col-span-2">
                {/* 分类筛选 */}
                <motion.div
                  className="flex flex-wrap gap-2 mb-8"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.2 }}
                >
                  {NEWS_CATEGORIES.map((category) => (
                    <motion.button
                      key={category.id}
                      onClick={() => handleCategoryChange(category.id)}
                      className={`px-5 py-2 text-sm font-medium rounded-lg transition-all ${
                        activeCategory === category.id
                          ? 'bg-primary text-white shadow-lg shadow-primary/25'
                          : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-200'
                      }`}
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                    >
                      {category.label}
                    </motion.button>
                  ))}
                </motion.div>

                {/* 新闻数量提示 */}
                <motion.p
                  className="text-sm text-gray-500 mb-6"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ delay: 0.3 }}
                >
                  共 <span className="font-medium text-primary">{filteredNews.length}</span> 条新闻
                </motion.p>

                {/* 新闻列表 */}
                <AnimatePresence mode="wait">
                  <motion.div
                    key={`${activeCategory}-${currentPage}`}
                    className="grid sm:grid-cols-2 gap-6"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.3 }}
                  >
                    {currentNews.map((news, index) => (
                      <NewsCard key={news.id} news={news} index={index} />
                    ))}
                  </motion.div>
                </AnimatePresence>

                {/* 空状态 */}
                {currentNews.length === 0 && (
                  <motion.div
                    className="text-center py-16"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                  >
                    <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                      <Clock size={32} className="text-gray-400" />
                    </div>
                    <h3 className="text-lg font-medium text-gray-600 mb-2">
                      暂无新闻
                    </h3>
                    <p className="text-gray-400">
                      该分类下暂无新闻，请选择其他分类
                    </p>
                  </motion.div>
                )}

                {/* 分页 */}
                {totalPages > 1 && (
                  <Pagination
                    currentPage={currentPage}
                    totalPages={totalPages}
                    onPageChange={setCurrentPage}
                  />
                )}
              </div>

              {/* 右侧侧边栏 */}
              <div className="lg:col-span-1">
                <div className="sticky top-24 space-y-8">
                  {/* 热门新闻 */}
                  <motion.div
                    className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6"
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.3 }}
                  >
                    <div className="flex items-center gap-3 mb-6">
                      <div className="p-2 bg-red-100 rounded-lg">
                        <TrendingUp size={20} className="text-red-500" />
                      </div>
                      <h3 className="text-lg font-semibold text-primary-dark">
                        热门新闻
                      </h3>
                    </div>
                    <div className="space-y-3">
                      {hotNews.map((news, index) => (
                        <HotNewsWidget key={news.id} news={news} rank={index + 1} />
                      ))}
                    </div>
                  </motion.div>

                  {/* 关注我们 */}
                  <motion.div
                    className="bg-gradient-to-br from-primary to-primary-light rounded-2xl p-6 text-white"
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.4 }}
                  >
                    <h3 className="text-lg font-semibold mb-4">关注我们</h3>
                    <p className="text-white/80 text-sm mb-4">
                      第一时间获取最新企业动态和行业资讯
                    </p>
                    <div className="flex gap-3">
                      <motion.button
                        className="flex-1 py-2 bg-white/20 rounded-lg text-sm font-medium hover:bg-white/30 transition-colors"
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                      >
                        微信公众号
                      </motion.button>
                      <motion.button
                        className="flex-1 py-2 bg-white/20 rounded-lg text-sm font-medium hover:bg-white/30 transition-colors"
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                      >
                        官方微博
                      </motion.button>
                    </div>
                  </motion.div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>

      {/* 页脚 */}
      <Footer />
    </motion.div>
  );
};

export default News;
