"use client"

import { useState, useMemo } from "react"
import Link from "next/link"
import { ArrowRight, TrendingUp, Eye, FileText, Video, BookOpen } from "lucide-react"
import { Button } from "@/components/ui/button"

interface Example {
  id: string
  title: string
  description: string
  category: string
  views: string
}

const categories = [
  { name: "All", icon: TrendingUp },
  { name: "Research Papers", icon: FileText },
  { name: "Analyzed Videos", icon: Video },
  { name: "Books", icon: BookOpen },
]

const ITEMS_PER_PAGE = 9

export default function TrendingList({ initialExamples }: { initialExamples: Example[] }) {
  const [selectedCategory, setSelectedCategory] = useState("All")
  const [visibleCount, setVisibleCount] = useState(ITEMS_PER_PAGE)

  const filteredExamples = useMemo(() => {
    if (selectedCategory === "All") return initialExamples
    return initialExamples.filter(ex => ex.category === selectedCategory)
  }, [selectedCategory, initialExamples])

  const paginatedExamples = filteredExamples.slice(0, visibleCount)
  const hasMore = visibleCount < filteredExamples.length

  const handleLoadMore = () => {
    setVisibleCount(prev => prev + ITEMS_PER_PAGE)
  }

  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category)
    setVisibleCount(ITEMS_PER_PAGE) // Reset pagination when category changes
  }

  return (
    <>
      {/* Integrated Categories */}
      <div className="flex items-center justify-center gap-3 overflow-x-auto pb-4 -mx-4 px-4 sm:mx-0 sm:px-0 no-scrollbar mb-4">
        {categories.map((category, index) => (
          <button
            key={index}
            onClick={() => handleCategoryChange(category.name)}
            className={`flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-bold whitespace-nowrap transition-all border ${
              selectedCategory === category.name
                ? "bg-primary text-primary-foreground border-primary shadow-lg shadow-primary/20 scale-105"
                : "bg-card text-muted-foreground border-border hover:border-primary/50 hover:bg-muted/50"
            }`}
          >
            <category.icon className="w-4 h-4" />
            {category.name}
          </button>
        ))}
      </div>

      {/* Examples Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 max-w-[1100px] mx-auto">
        {paginatedExamples.map((example: Example, index) => {
          const CategoryIcon = categories.find(c => c.name === example.category)?.icon || FileText;

          return (
            <article
              key={index}
              className="group relative bg-card/40 backdrop-blur-md border border-border/50 rounded-2xl overflow-hidden hover:border-primary/50 hover:shadow-2xl hover:shadow-primary/5 transition-all duration-500 flex flex-col"
            >
              <Link href={`/trending/${example.id}`} className="flex flex-col h-full">
                {/* Image/Preview Area */}
                <div className="aspect-video bg-gradient-to-br from-primary/5 via-accent/5 to-primary/10 flex items-center justify-center relative overflow-hidden group-hover:scale-105 transition-transform duration-700">
                  {/* Animated Grid Background */}
                  <div className="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.05)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.05)_1px,transparent_1px)] bg-[size:20px_20px] [mask-image:radial-gradient(ellipse_50%_50%_at_50%_50%,#000_70%,transparent_100%)] opacity-30 group-hover:opacity-100 transition-opacity duration-700 dark:bg-[linear-gradient(rgba(255,255,255,0.05)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.05)_1px,transparent_1px)] light:bg-[linear-gradient(rgba(0,0,0,0.03)_1px,transparent_1px),linear-gradient(90deg,rgba(0,0,0,0.03)_1px,transparent_1px))]" />
                  
                  {/* Animated Nodes / Connections */}
                  <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-700">
                    <div className="absolute top-[20%] left-[20%] w-2 h-2 rounded-full bg-primary/60 shadow-[0_0_10px_rgba(var(--primary),0.5)] animate-ping" style={{ animationDuration: '3s' }} />
                    <div className="absolute bottom-[25%] right-[20%] w-3 h-3 rounded-full bg-accent/60 shadow-[0_0_10px_rgba(var(--accent),0.5)] animate-pulse" />
                    <div className="absolute top-[30%] right-[30%] w-1.5 h-1.5 rounded-full bg-primary/40 animate-bounce" style={{ animationDuration: '2s' }} />
                    <div className="absolute bottom-[30%] left-[30%] w-2.5 h-2.5 rounded-full bg-accent/50 animate-pulse" style={{ animationDelay: '150ms' }} />
                    <div className="absolute top-[60%] left-[10%] w-1.5 h-1.5 rounded-full bg-primary/40 animate-ping" style={{ animationDuration: '4s' }} />
                    <div className="absolute top-[15%] right-[45%] w-2 h-2 rounded-full bg-accent/40 animate-pulse" style={{ animationDelay: '300ms' }} />
                    
                    {/* Decorative lines connecting nodes */}
                    <svg className="absolute inset-0 w-full h-full text-primary/30 dark:text-primary/20" preserveAspectRatio="none">
                      <line x1="20%" y1="20%" x2="50%" y2="50%" stroke="currentColor" strokeWidth="1" strokeDasharray="4 4" className="animate-pulse" style={{ animationDuration: '2s' }} />
                      <line x1="80%" y1="75%" x2="50%" y2="50%" stroke="currentColor" strokeWidth="1" strokeDasharray="4 4" className="animate-pulse" style={{ animationDelay: '75ms', animationDuration: '3s' }} />
                      <line x1="70%" y1="30%" x2="50%" y2="50%" stroke="currentColor" strokeWidth="1" strokeDasharray="2 2" className="animate-pulse" style={{ animationDelay: '200ms' }} />
                      <line x1="30%" y1="70%" x2="50%" y2="50%" stroke="currentColor" strokeWidth="1" strokeDasharray="2 2" className="animate-pulse" style={{ animationDelay: '400ms' }} />
                      <line x1="10%" y1="60%" x2="30%" y2="70%" stroke="currentColor" strokeWidth="0.5" strokeDasharray="2 2" />
                      <line x1="45%" y1="15%" x2="20%" y2="20%" stroke="currentColor" strokeWidth="0.5" strokeDasharray="2 2" />
                    </svg>
                  </div>

                  <div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_50%,rgba(255,255,255,0.1)_0%,rgba(0,0,0,0.05)_100%)] dark:bg-[radial-gradient(circle_at_50%_50%,rgba(255,255,255,0.05)_0%,rgba(0,0,0,0.2)_100%)] transition-all duration-700" />
                  
                  <div className="relative z-10 text-center p-4 transition-transform duration-500 group-hover:scale-110">
                    <div className="w-14 h-14 bg-white/10 dark:bg-black/10 backdrop-blur-md rounded-2xl flex items-center justify-center mx-auto mb-3 border border-white/20 dark:border-white/5 shadow-xl group-hover:bg-primary group-hover:text-primary-foreground group-hover:shadow-[0_0_30px_rgba(var(--primary),0.3)] group-hover:-rotate-3 transition-all duration-500 relative">
                      <div className="absolute inset-0 rounded-2xl bg-primary/20 blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
                      <CategoryIcon className="w-7 h-7 relative z-10 transition-transform duration-500 group-hover:scale-110" />
                    </div>
                    <div className="flex flex-col items-center h-4 justify-center">
                      <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest opacity-0 group-hover:opacity-100 transition-all duration-300 transform translate-y-2 group-hover:translate-y-0">
                        Interactive Map
                      </p>
                      <div className="h-0.5 w-0 bg-primary mt-1 group-hover:w-8 transition-all duration-500 rounded-full opacity-0 group-hover:opacity-100" />
                    </div>
                  </div>
                </div>

                {/* Content Area */}
                <div className="p-4 flex flex-col flex-1 relative bg-gradient-to-b from-transparent to-card/50">
                  <div className="flex items-center justify-between gap-3 mb-2">
                    <span className="px-2 py-0.5 rounded-md bg-primary/10 text-[10px] font-bold text-primary uppercase tracking-wider">
                      {example.category}
                    </span>
                    <span className="flex items-center gap-1.5 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                      <Eye className="w-3 h-3 text-primary/60" />
                      {example.views} views
                    </span>
                  </div>

                  <h3 className="text-sm sm:text-base font-bold text-foreground mb-1.5 line-clamp-2 group-hover:text-primary transition-colors leading-snug">
                    {example.title}
                  </h3>
                  
                  <p className="text-xs text-muted-foreground line-clamp-2 mb-2 flex-1 leading-relaxed">
                    {example.description}
                  </p>

                  <div className="mt-auto pt-2 flex items-center justify-between border-t border-border/30">
                    <span className="text-xs font-bold text-primary flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-all -translate-x-2 group-hover:translate-x-0">
                      View Analysis <ArrowRight className="w-3 h-3" />
                    </span>
                    <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-primary-foreground transition-all duration-500">
                      <ArrowRight className="w-3.5 h-3.5" />
                    </div>
                  </div>
                </div>
              </Link>
            </article>
          )
        })}
      </div>

      {/* Load More */}
      {hasMore && (
        <div className="text-center mt-8">
          <Button variant="outline" size="lg" onClick={handleLoadMore}>
            Load More Examples
          </Button>
        </div>
      )}
      
      {paginatedExamples.length === 0 && (
        <div className="text-center py-20">
          <p className="text-muted-foreground">No examples found for this category.</p>
        </div>
      )}
    </>
  )
}
