'use client';

import { useState, useMemo, ChangeEvent, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useReducedMotion } from '@/hooks/use-reduced-motion';
import { NEWS, COMPANY_INFO } from '@/lib/constants';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { StaticLink } from '@/components/ui/static-link';
import { LoadingState } from '@/components/ui/loading-state';
import { InkCard } from '@/components/ui/ink-wash';
import { Search, Calendar, ChevronLeft, ChevronRight, ArrowRight, Newspaper } from 'lucide-react';

const EASE = [0.25, 1, 0.5, 1] as const;

const categories = ['全部', '公司新闻', '研发动态'];
const ITEMS_PER_PAGE = 9;

export default function NewsListPage() {
  const shouldReduceMotion = useReducedMotion();
  const [selectedCategory, setSelectedCategory] = useState('全部');
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const timer = setTimeout(() => setIsLoading(false), 600);
    return () => clearTimeout(timer);
  }, []);

  const filteredNews = useMemo(() => {
    return NEWS.filter((newsItem) => {
      const matchesCategory = selectedCategory === '全部' || newsItem.category === selectedCategory;
      const matchesSearch =
        newsItem.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        newsItem.excerpt.toLowerCase().includes(searchQuery.toLowerCase());
      return matchesCategory && matchesSearch;
    });
  }, [selectedCategory, searchQuery]);

  const totalPages = Math.ceil(filteredNews.length / ITEMS_PER_PAGE);
  const paginatedNews = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    return filteredNews.slice(startIndex, startIndex + ITEMS_PER_PAGE);
  }, [filteredNews, currentPage]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category);
    setCurrentPage(1);
  };

  const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    setCurrentPage(1);
  };

  return (
    <div className="min-h-screen bg-[var(--color-bg-primary)]">
      {/* Hero */}
      <section className="relative pt-32 pb-12 overflow-hidden">
        <div className="container-wide relative z-10">
          <motion.div
            initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, ease: EASE }}
            className="max-w-3xl"
          >
            <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-[var(--color-brand-primary-bg)] text-[var(--color-brand-primary)] text-xs font-medium border border-[var(--color-brand-primary)]/10 mb-6">
              新闻动态
            </div>
            <p className="text-base sm:text-lg text-[var(--color-text-muted)] mb-3">
              了解行业趋势，把握数字化脉搏
            </p>
            <h1 className="text-4xl md:text-5xl lg:text-6xl tracking-tight mb-6 leading-[1.12]">
              新闻<span className="text-[var(--color-brand-primary)] font-calligraphy">动态</span>
            </h1>
            <p className="text-base sm:text-lg text-[var(--color-text-muted)] max-w-lg leading-relaxed">
              {COMPANY_INFO.displayName}最新动态、产品更新与行业洞察
            </p>
          </motion.div>
        </div>
      </section>

      {/* Filters + List */}
      <section className="pb-16 md:pb-24">
        <div className="container-wide">
          <motion.div
            initial={shouldReduceMotion ? {} : { opacity: 0, y: 16 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5, ease: EASE }}
            className="mb-10 space-y-4"
          >
            <div className="flex flex-wrap gap-2">
              {categories.map((category) => (
                <Button
                  key={category}
                  variant={selectedCategory === category ? 'default' : 'outline'}
                  onClick={() => handleCategoryChange(category)}
                  className={
                    selectedCategory === category
                      ? 'bg-[var(--color-brand-primary)] hover:bg-[var(--color-brand-primary-hover)] text-white'
                      : ''
                  }
                >
                  {category}
                </Button>
              ))}
            </div>

            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-[var(--color-text-muted)] w-5 h-5" />
              <Input
                type="text"
                placeholder="搜索新闻..."
                value={searchQuery}
                onChange={handleSearchChange}
                className="pl-10"
                aria-label="搜索新闻"
              />
            </div>
          </motion.div>

          {paginatedNews.length === 0 ? (
            <div className="text-center py-20">
              <Newspaper className="w-12 h-12 text-[var(--color-border)] mx-auto mb-4" />
              <p className="text-lg text-[var(--color-text-muted)]">没有找到相关新闻</p>
            </div>
          ) : (
            <LoadingState isLoading={isLoading} variant="list">
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
                  {paginatedNews.map((newsItem, index) => (
                    <motion.div
                      key={newsItem.id}
                      initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
                      whileInView={{ opacity: 1, y: 0 }}
                      viewport={{ once: true }}
                      transition={{ duration: 0.5, delay: index * 0.08, ease: EASE }}
                    >
                      <StaticLink href={`/news/${newsItem.id}`}>
                        <InkCard padding="none" interactive className="h-full overflow-hidden group">
                          {newsItem.image ? (
                            <div className="aspect-video bg-[var(--color-bg-tertiary)] overflow-hidden">
                              <img
                                src={newsItem.image}
                                alt={newsItem.title}
                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                              />
                            </div>
                          ) : (
                            <div className="aspect-video bg-gradient-to-br from-[var(--color-brand-primary-bg)] to-[var(--color-bg-tertiary)] flex items-center justify-center">
                              <Newspaper className="w-12 h-12 text-[var(--color-brand-primary)]/30" />
                            </div>
                          )}
                          <div className="p-6">
                            <div className="flex items-center gap-2 mb-3">
                              <Badge variant="secondary" className="text-xs">{newsItem.category}</Badge>
                              <div className="flex items-center gap-1 text-xs text-[var(--color-text-muted)]">
                                <Calendar className="w-3 h-3" />
                                {newsItem.date}
                              </div>
                            </div>
                            <h3 className="text-lg font-semibold text-[var(--color-text-primary)] mb-2 line-clamp-2 group-hover:text-[var(--color-brand-primary)] transition-colors duration-300">
                              {newsItem.title}
                            </h3>
                            <p className="text-sm text-[var(--color-text-muted)] line-clamp-3 mb-4 leading-relaxed">
                              {newsItem.excerpt}
                            </p>
                            <div className="flex items-center text-[var(--color-brand-primary)] text-sm font-medium">
                              阅读更多
                              <ArrowRight className="ml-1 w-4 h-4 group-hover:translate-x-1 transition-transform duration-300" />
                            </div>
                          </div>
                        </InkCard>
                      </StaticLink>
                    </motion.div>
                  ))}
                </div>

                {totalPages > 1 && (
                  <div className="flex justify-center items-center gap-2 mt-10">
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => handlePageChange(currentPage - 1)}
                      disabled={currentPage === 1}
                    >
                      <ChevronLeft className="w-4 h-4" />
                    </Button>
                    {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                      <Button
                        key={page}
                        variant={currentPage === page ? 'default' : 'outline'}
                        size="icon"
                        onClick={() => handlePageChange(page)}
                        className={
                          currentPage === page
                            ? 'bg-[var(--color-brand-primary)] hover:bg-[var(--color-brand-primary-hover)] text-white'
                            : ''
                        }
                      >
                        {page}
                      </Button>
                    ))}
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => handlePageChange(currentPage + 1)}
                      disabled={currentPage === totalPages}
                    >
                      <ChevronRight className="w-4 h-4" />
                    </Button>
                  </div>
                )}
              </>
            </LoadingState>
          )}
        </div>
      </section>
    </div>
  );
}
