'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { api } from '@/lib/api'
import { 
  BookOpen, 
  Calendar, 
  Clock, 
  Eye, 
  ArrowRight,
  Loader2,
  FileText,
  TrendingUp,
} from 'lucide-react'
import clsx from 'clsx'

interface BlogPost {
  id: number
  title: string
  slug: string
  excerpt: string | null
  cover_image: string | null
  category: string | null
  tags: string[]
  is_published: boolean
  published_at: string | null
  created_at: string
  view_count: number
  author: {
    id: number
    name: string | null
  }
}

interface Category {
  name: string
  count: number
}

export default function BlogPage() {
  const [posts, setPosts] = useState<BlogPost[]>([])
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
  const [total, setTotal] = useState(0)

  useEffect(() => {
    loadBlogData()
  }, [selectedCategory])

  const loadBlogData = async () => {
    setLoading(true)
    try {
      const [postsData, categoriesData] = await Promise.all([
        api.getBlogPosts(12, 0, selectedCategory || undefined),
        api.getBlogCategories(),
      ])
      setPosts(postsData.posts)
      setTotal(postsData.total)
      setCategories(categoriesData.categories)
    } catch (error) {
      console.error('Failed to load blog:', error)
    } finally {
      setLoading(false)
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    })
  }

  const estimateReadTime = (excerpt: string | null) => {
    if (!excerpt) return '3 min'
    const words = excerpt.split(' ').length
    const minutes = Math.ceil(words / 200) + 2
    return `${minutes} min`
  }

  const featuredPost = posts[0]
  const otherPosts = posts.slice(1)

  return (
    <div className="min-h-screen bg-background relative overflow-hidden">
      {/* Background Effects */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
        <div className="absolute top-[40%] left-[-10%] w-[400px] h-[400px] bg-accent/[0.02] rounded-full blur-[80px]" />
        <div 
          className="absolute inset-0 opacity-[0.015]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.1) 1px, transparent 1px)`,
            backgroundSize: '64px 64px',
          }}
        />
      </div>

      <Header />

      <main className="relative flex-1 pt-32 sm:pt-40 pb-20 sm:pb-28 px-4 sm:px-6">
        <div className="max-w-7xl mx-auto">
          {/* Hero Header */}
          <div className="text-center mb-20 animate-fade-in">
            <span className="text-sm font-semibold text-accent uppercase tracking-wider">Field Briefings</span>
            
            <h1 className="mt-4 font-display text-[2.75rem] sm:text-[4rem] md:text-[5rem] leading-[0.95] tracking-[-0.03em] text-foreground mb-8">
              The Hunt<br />
              <span className="text-accent">Begins Here.</span>
            </h1>
            
            <p className="text-lg sm:text-xl text-foreground-muted max-w-2xl mx-auto leading-relaxed">
              Expert strategies, market insights, and proven tactics from professional domain hunters.
            </p>
          </div>

          {/* Categories */}
          {categories.length > 0 && (
            <div className="flex flex-wrap items-center justify-center gap-3 mb-16">
              <button
                onClick={() => setSelectedCategory(null)}
                className={clsx(
                  "px-5 py-2.5 text-sm font-medium rounded-full transition-all duration-300",
                  !selectedCategory
                    ? "bg-accent text-background shadow-lg shadow-accent/25"
                    : "bg-background-secondary/50 border border-border text-foreground-muted hover:text-foreground hover:border-accent/30"
                )}
              >
                All Posts
              </button>
              {categories.map((cat) => (
                <button
                  key={cat.name}
                  onClick={() => setSelectedCategory(cat.name)}
                  className={clsx(
                    "px-5 py-2.5 text-sm font-medium rounded-full transition-all duration-300",
                    selectedCategory === cat.name
                      ? "bg-accent text-background shadow-lg shadow-accent/25"
                      : "bg-background-secondary/50 border border-border text-foreground-muted hover:text-foreground hover:border-accent/30"
                  )}
                >
                  {cat.name}
                </button>
              ))}
            </div>
          )}

          {/* Posts */}
          {loading ? (
            <div className="flex items-center justify-center py-32">
              <div className="text-center">
                <Loader2 className="w-10 h-10 text-accent animate-spin mx-auto mb-4" />
                <p className="text-foreground-muted">Loading insights...</p>
              </div>
            </div>
          ) : posts.length === 0 ? (
            <div className="text-center py-32">
              <div className="w-20 h-20 bg-accent/10 rounded-full flex items-center justify-center mx-auto mb-8">
                <FileText className="w-10 h-10 text-accent" />
              </div>
              <h2 className="text-3xl font-display text-foreground mb-4">Coming Soon</h2>
              <p className="text-foreground-muted max-w-md mx-auto">
                We&apos;re preparing expert content. Check back soon for domain hunting insights and strategies.
              </p>
            </div>
          ) : (
            <>
              {/* Featured Post */}
              {featuredPost && !selectedCategory && (
                <Link
                  href={`/blog/${featuredPost.slug}`}
                  className="group relative block mb-16 animate-fade-in"
                >
                  <div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-background-secondary to-background-tertiary border border-border hover:border-accent/30 transition-all duration-500">
                    <div className="grid lg:grid-cols-2 gap-0">
                      {/* Image */}
                      <div className="relative aspect-[16/10] lg:aspect-auto lg:min-h-[400px] overflow-hidden">
                        {featuredPost.cover_image ? (
                          <Image
                            src={featuredPost.cover_image}
                            alt={featuredPost.title}
                            fill
                            className="object-cover group-hover:scale-105 transition-transform duration-700"
                          />
                        ) : (
                          <div className="absolute inset-0 bg-gradient-to-br from-accent/20 to-accent/5 flex items-center justify-center">
                            <BookOpen className="w-20 h-20 text-accent/30" />
                          </div>
                        )}
                        <div className="absolute inset-0 bg-gradient-to-t from-background/80 via-transparent to-transparent lg:bg-gradient-to-r" />
                        
                        {/* Featured Badge */}
                        <div className="absolute top-6 left-6 flex items-center gap-2 px-4 py-2 bg-accent text-background rounded-full text-sm font-medium">
                          <TrendingUp className="w-4 h-4" />
                          Featured
                        </div>
                      </div>

                      {/* Content */}
                      <div className="relative p-8 lg:p-12 flex flex-col justify-center">
                        {featuredPost.category && (
                          <span className="inline-block w-fit px-3 py-1 bg-accent/10 text-accent text-xs font-semibold uppercase tracking-wider rounded-full mb-6">
                            {featuredPost.category}
                          </span>
                        )}
                        
                        <h2 className="text-2xl sm:text-3xl lg:text-4xl font-display text-foreground mb-4 group-hover:text-accent transition-colors duration-300 leading-tight">
                          {featuredPost.title}
                        </h2>
                        
                        {featuredPost.excerpt && (
                          <p className="text-foreground-muted text-lg mb-6 line-clamp-3 leading-relaxed">
                            {featuredPost.excerpt}
                          </p>
                        )}

                        <div className="flex items-center gap-6 text-sm text-foreground-subtle mb-8">
                          <span className="flex items-center gap-2">
                            <Calendar className="w-4 h-4" />
                            {featuredPost.published_at ? formatDate(featuredPost.published_at) : formatDate(featuredPost.created_at)}
                          </span>
                          <span className="flex items-center gap-2">
                            <Clock className="w-4 h-4" />
                            {estimateReadTime(featuredPost.excerpt)}
                          </span>
                          <span className="flex items-center gap-2">
                            <Eye className="w-4 h-4" />
                            {featuredPost.view_count}
                          </span>
                        </div>

                        <span className="inline-flex items-center gap-2 text-accent font-medium group-hover:gap-4 transition-all duration-300">
                          Read Article
                          <ArrowRight className="w-5 h-5" />
                        </span>
                      </div>
                    </div>
                  </div>
                </Link>
              )}

              {/* Posts Grid */}
              <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8 mb-16">
                {(selectedCategory ? posts : otherPosts).map((post, index) => (
                  <Link
                    key={post.id}
                    href={`/blog/${post.slug}`}
                    className="group relative flex flex-col bg-background-secondary/30 backdrop-blur-sm border border-border rounded-2xl overflow-hidden hover:border-accent/40 hover:shadow-xl hover:shadow-accent/5 transition-all duration-500"
                    style={{ 
                      animationDelay: `${index * 100}ms`,
                      animation: 'fadeInUp 0.6s ease-out forwards',
                      opacity: 0,
                    }}
                  >
                    {/* Cover */}
                    <div className="relative aspect-[16/10] overflow-hidden">
                      {post.cover_image ? (
                        <Image
                          src={post.cover_image}
                          alt={post.title}
                          fill
                          className="object-cover group-hover:scale-110 transition-transform duration-700"
                        />
                      ) : (
                        <div className="absolute inset-0 bg-gradient-to-br from-accent/10 via-accent/5 to-transparent flex items-center justify-center">
                          <BookOpen className="w-12 h-12 text-accent/20 group-hover:text-accent/40 transition-colors" />
                        </div>
                      )}
                      <div className="absolute inset-0 bg-gradient-to-t from-background via-transparent to-transparent opacity-60" />
                      
                      {post.category && (
                        <span className="absolute top-4 left-4 px-3 py-1.5 bg-background/90 backdrop-blur-sm text-xs font-semibold text-foreground rounded-full border border-border/50">
                          {post.category}
                        </span>
                      )}
                    </div>

                    {/* Content */}
                    <div className="flex-1 p-6 flex flex-col">
                      <h3 className="text-xl font-display text-foreground mb-3 group-hover:text-accent transition-colors duration-300 line-clamp-2 leading-snug">
                        {post.title}
                      </h3>
                      
                      {post.excerpt && (
                        <p className="text-foreground-muted text-sm mb-6 line-clamp-2 leading-relaxed flex-1">
                          {post.excerpt}
                        </p>
                      )}

                      <div className="flex items-center justify-between text-xs text-foreground-subtle pt-4 border-t border-border/50">
                        <div className="flex items-center gap-4">
                          <span className="flex items-center gap-1.5">
                            <Calendar className="w-3.5 h-3.5" />
                            {post.published_at ? formatDate(post.published_at) : formatDate(post.created_at)}
                          </span>
                          <span className="flex items-center gap-1.5">
                            <Eye className="w-3.5 h-3.5" />
                            {post.view_count}
                          </span>
                        </div>
                        <ArrowRight className="w-4 h-4 text-accent opacity-0 group-hover:opacity-100 transform translate-x-0 group-hover:translate-x-1 transition-all duration-300" />
                      </div>
                    </div>
                  </Link>
                ))}
              </div>

              {/* Load More */}
              {posts.length < total && (
                <div className="text-center">
                  <button
                    onClick={async () => {
                      try {
                        const moreData = await api.getBlogPosts(12, posts.length, selectedCategory || undefined)
                        setPosts([...posts, ...moreData.posts])
                      } catch (error) {
                        console.error('Failed to load more posts:', error)
                      }
                    }}
                    className="group inline-flex items-center gap-3 px-8 py-4 bg-background-secondary/50 border border-border rounded-full text-foreground font-medium hover:border-accent/50 hover:bg-accent/5 transition-all duration-300"
                  >
                    Load More Articles
                    <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                  </button>
                </div>
              )}
            </>
          )}

          {/* Newsletter CTA */}
          <div className="mt-24 relative">
            <div className="absolute inset-0 bg-gradient-to-r from-accent/10 via-accent/5 to-accent/10 rounded-3xl blur-xl" />
            <div className="relative p-10 sm:p-14 bg-background-secondary/50 backdrop-blur-sm border border-accent/20 rounded-3xl text-center">
              <h3 className="text-2xl sm:text-3xl font-display text-foreground mb-4">
                Get hunting tips in your inbox
              </h3>
              <p className="text-foreground-muted mb-8 max-w-xl mx-auto">
                Join domain hunters who receive weekly insights, market trends, and exclusive strategies.
              </p>
              <div className="flex flex-col sm:flex-row gap-4 justify-center max-w-md mx-auto">
                <input
                  type="email"
                  placeholder="Enter your email"
                  className="flex-1 px-5 py-3.5 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent/50 transition-colors"
                />
                <button className="px-8 py-3.5 bg-accent text-background rounded-xl font-medium hover:bg-accent-hover transition-colors whitespace-nowrap">
                  Subscribe
                </button>
              </div>
            </div>
          </div>
        </div>
      </main>

      <Footer />

      <style jsx>{`
        @keyframes fadeInUp {
          from {
            opacity: 0;
            transform: translateY(20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </div>
  )
}
