'use client';

import { useState, useMemo, ChangeEvent } from 'react';
import { motion } from 'framer-motion';
import { ScrollReveal, StaggerReveal } from '@/components/ui/scroll-reveal';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Search, Calendar, ArrowRight, Newspaper, ChevronLeft, ChevronRight } from 'lucide-react';
import { NEWS, COMPANY_INFO } from '@/lib/constants';
import { cn } from '@/lib/utils';

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

function GrainOverlay() {
  return (
    <div
      className="absolute inset-0 pointer-events-none opacity-[0.03] mix-blend-overlay"
      style={{
        backgroundImage:
          "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E\")",
      }}
    />
  );
}

function SectionLabel({ children, className = '' }: { children: React.ReactNode; className?: string }) {
  return (
    <div className={cn('flex items-center gap-5 mb-7', className)}>
      <div className="w-14 h-px bg-brand" />
      <span className="text-[11px] tracking-[0.4em] uppercase font-bold text-brand">
        {children}
      </span>
      <div className="w-14 h-px bg-brand" />
    </div>
  );
}

function NewsCard({ newsItem, index }: { newsItem: typeof NEWS[0]; index: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5, delay: index * 0.08, ease: EASE_OUT }}
    >
      <a
        href={`/news/${newsItem.id}`}
        className="group relative block border border-white/10 hover:border-brand/40 bg-ink transition-all duration-600 hover:-translate-y-2 overflow-hidden h-full"
      >
        <div className="absolute top-0 left-0 right-0 h-1 bg-brand scale-x-0 group-hover:scale-x-100 transition-transform duration-700 origin-left" />

        {newsItem.image ? (
          <div className="aspect-video bg-ink-light overflow-hidden">
            <img
              src={newsItem.image}
              alt={newsItem.title}
              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
            />
          </div>
        ) : (
          <div className="aspect-video bg-gradient-to-br from-brand/10 to-ink-light flex items-center justify-center">
            <Newspaper className="w-12 h-12 text-brand/30" />
          </div>
        )}

        <div className="p-6 lg:p-8">
          <div className="flex items-center gap-3 mb-4">
            <Badge variant="outline" className="text-xs border-brand/30 text-brand">
              {newsItem.category}
            </Badge>
            <div className="flex items-center gap-1.5 text-xs text-white/50">
              <Calendar className="w-3.5 h-3.5" />
              {newsItem.date}
            </div>
          </div>

          <h3 className="text-lg font-semibold text-white mb-3 line-clamp-2 group-hover:text-brand transition-colors duration-300 leading-snug">
            {newsItem.title}
          </h3>

          <p className="text-sm text-white/50 line-clamp-3 mb-5 leading-relaxed">
            {newsItem.excerpt}
          </p>

          <div className="flex items-center text-brand text-sm font-medium">
            阅读全文
            <ArrowRight className="ml-2 w-4 h-4 group-hover:translate-x-1 transition-transform duration-300" />
          </div>
        </div>
      </a>
    </motion.div>
  );
}

export default function NewsContentV1() {
  const [selectedCategory, setSelectedCategory] = useState('全部');
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);

  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-ink text-white overflow-x-hidden">
      {/* Hero Section */}
      <section className="relative pt-32 pb-24 lg:pt-40 lg:pb-32 overflow-hidden">
        <GrainOverlay />

        <div className="absolute inset-0 bg-gradient-to-b from-ink-light/50 to-ink pointer-events-none" />

        <div className="max-w-container mx-auto px-6 lg:px-10 relative z-10">
          <ScrollReveal>
            <SectionLabel>News & Insights</SectionLabel>
          </ScrollReveal>

          <ScrollReveal delay={0.1}>
            <h1 className="mt-8 text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold tracking-tight leading-[1.1]">
              新闻与
              <span className="block mt-2 text-brand">洞察</span>
            </h1>
          </ScrollReveal>

          <ScrollReveal delay={0.2}>
            <p className="mt-8 text-lg md:text-xl text-white/60 max-w-2xl leading-relaxed">
              {COMPANY_INFO.displayName}最新动态、产品更新与行业洞察。了解数字化趋势，把握技术脉搏。
            </p>
          </ScrollReveal>
        </div>
      </section>

      {/* Filter + News List Section */}
      <section className="relative py-24 lg:py-32 overflow-hidden bg-ink-light">
        <GrainOverlay />

        <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-white/12 to-transparent" />

        <div className="max-w-container mx-auto px-6 lg:px-10 relative z-10">
          {/* Filters */}
          <ScrollReveal className="mb-16 space-y-6">
            <div className="flex flex-wrap gap-3">
              {categories.map((category) => (
                <Button
                  key={category}
                  variant={selectedCategory === category ? 'primary' : 'outline'}
                  onClick={() => handleCategoryChange(category)}
                >
                  {category}
                </Button>
              ))}
            </div>

            <div className="relative max-w-md">
              <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-white/40 w-5 h-5 pointer-events-none" />
              <Input
                type="text"
                placeholder="搜索新闻..."
                value={searchQuery}
                onChange={handleSearchChange}
                className="pl-12 h-12 bg-ink border-white/10 text-white placeholder:text-white/30 focus:border-brand/50"
              />
            </div>
          </ScrollReveal>

          {/* News Grid */}
          {paginatedNews.length === 0 ? (
            <ScrollReveal>
              <div className="text-center py-24">
                <Newspaper className="w-16 h-16 text-white/20 mx-auto mb-6" />
                <p className="text-xl text-white/50">没有找到相关新闻</p>
                <p className="mt-2 text-white/30">试试其他关键词或分类</p>
              </div>
            </ScrollReveal>
          ) : (
            <>
              <StaggerReveal
                className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8"
                delayChildren={0.05}
              >
                {paginatedNews.map((newsItem, index) => (
                  <NewsCard key={newsItem.id} newsItem={newsItem} index={index} />
                ))}
              </StaggerReveal>

              {/* Pagination */}
              {totalPages > 1 && (
                <ScrollReveal>
                  <div className="flex justify-center items-center gap-2 mt-16">
                    <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 ? 'primary' : 'outline'}
                        size="icon"
                        onClick={() => handlePageChange(page)}
                      >
                        {page}
                      </Button>
                    ))}
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => handlePageChange(currentPage + 1)}
                      disabled={currentPage === totalPages}
                    >
                      <ChevronRight className="w-4 h-4" />
                    </Button>
                  </div>
                </ScrollReveal>
              )}
            </>
          )}
        </div>
      </section>

      {/* CTA Section */}
      <section className="relative py-36 lg:py-44 overflow-hidden bg-ink">
        <GrainOverlay />

        <div className="absolute inset-0 pointer-events-none">
          <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] rounded-full opacity-[0.08] blur-3xl bg-brand" />
        </div>

        <div className="max-w-container mx-auto px-6 lg:px-10 relative z-10">
          <ScrollReveal className="max-w-3xl mx-auto text-center">
            <SectionLabel className="justify-center">
              <div className="flex items-center gap-5">
                <div className="w-14 h-px bg-brand" />
                <span className="text-[11px] tracking-[0.4em] uppercase font-bold text-brand">
                  Get in Touch
                </span>
                <div className="w-14 h-px bg-brand" />
              </div>
            </SectionLabel>

            <h2 className="text-3xl md:text-4xl lg:text-6xl font-bold text-white tracking-tight leading-tight mb-8">
              想了解更多？
            </h2>

            <p className="text-lg md:text-xl text-white/60 leading-relaxed mb-12">
              无论您有合作意向还是想探讨技术趋势，我们都欢迎与您交流。
            </p>

            <div className="flex flex-wrap gap-6 justify-center">
              <Button size="xl" asChild>
                <a href="/contact">
                  联系我们
                  <ArrowRight className="w-5 h-5 ml-2" />
                </a>
              </Button>
              <Button size="xl" variant="outline" asChild>
                <a href="/about">了解公司</a>
              </Button>
            </div>
          </ScrollReveal>
        </div>
      </section>
    </div>
  );
}
