'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
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 { 
  Calendar, 
  Clock, 
  Eye, 
  ArrowLeft,
  Tag,
  Loader2,
  User,
  BookOpen,
  Twitter,
  Linkedin,
  Copy,
  Check,
} from 'lucide-react'

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

export default function BlogPostPage() {
  const params = useParams()
  const slug = params.slug as string
  
  const [post, setPost] = useState<BlogPost | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    if (slug) {
      loadPost()
    }
  }, [slug])

  const loadPost = async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await api.getBlogPost(slug)
      setPost(data)
    } catch (err) {
      setError('Blog post not found')
    } finally {
      setLoading(false)
    }
  }

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

  const estimateReadTime = (content: string) => {
    const words = content.split(/\s+/).length
    const minutes = Math.ceil(words / 200)
    return `${minutes} min read`
  }

  const handleCopyLink = async () => {
    await navigator.clipboard.writeText(window.location.href)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const shareOnTwitter = () => {
    const url = encodeURIComponent(window.location.href)
    const text = encodeURIComponent(post?.title || '')
    window.open(`https://twitter.com/intent/tweet?url=${url}&text=${text}`, '_blank')
  }

  const shareOnLinkedIn = () => {
    const url = encodeURIComponent(window.location.href)
    window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${url}`, '_blank')
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-10 h-10 text-accent animate-spin mx-auto mb-4" />
          <p className="text-foreground-muted">Loading article...</p>
        </div>
      </div>
    )
  }

  if (error || !post) {
    return (
      <div className="min-h-screen bg-background relative overflow-hidden flex flex-col">
        {/* Background */}
        <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>
        
        <Header />
        <main className="flex-1 flex items-center justify-center px-4 relative">
          <div className="text-center max-w-md">
            <div className="w-20 h-20 bg-accent/10 rounded-full flex items-center justify-center mx-auto mb-8">
              <BookOpen className="w-10 h-10 text-accent" />
            </div>
            <h1 className="text-3xl font-display text-foreground mb-4">Article Not Found</h1>
            <p className="text-foreground-muted mb-8 leading-relaxed">
              The article you&apos;re looking for doesn&apos;t exist or has been removed from our collection.
            </p>
            <Link
              href="/blog"
              className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-background rounded-xl font-medium hover:bg-accent-hover transition-all"
            >
              <ArrowLeft className="w-4 h-4" />
              Back to Briefings
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    )
  }

  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 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">
        <article className="max-w-4xl mx-auto">
          {/* Back Link */}
          <Link
            href="/blog"
            className="inline-flex items-center gap-2 text-foreground-muted hover:text-accent transition-colors mb-10 group"
          >
            <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
            <span className="text-sm font-medium">Back to Briefings</span>
          </Link>

          {/* Hero Header */}
          <header className="mb-12 animate-fade-in">
            <div className="flex flex-wrap items-center gap-4 mb-6">
              {post.category && (
                <span className="text-sm font-semibold text-accent uppercase tracking-wider">
                  {post.category}
                </span>
              )}
              <span className="flex items-center gap-1.5 text-sm text-foreground-subtle">
                <Clock className="w-4 h-4" />
                {estimateReadTime(post.content)}
              </span>
            </div>

            <h1 className="font-display text-[2.25rem] sm:text-[3rem] md:text-[3.75rem] leading-[1.05] tracking-[-0.03em] text-foreground mb-8">
              {post.title}
            </h1>

            {post.excerpt && (
              <p className="text-xl text-foreground-muted leading-relaxed mb-8 max-w-3xl">
                {post.excerpt}
              </p>
            )}

            {/* Meta Row */}
            <div className="flex flex-wrap items-center gap-6 pb-8 border-b border-border">
              <div className="flex items-center gap-4">
                {post.author.name && (
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-accent/10 rounded-full flex items-center justify-center">
                      <User className="w-5 h-5 text-accent" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-foreground">{post.author.name}</p>
                      <p className="text-xs text-foreground-subtle">Author</p>
                    </div>
                  </div>
                )}
              </div>
              
              <div className="flex items-center gap-4 text-sm text-foreground-subtle">
                <span className="flex items-center gap-2">
                  <Calendar className="w-4 h-4" />
                  {post.published_at ? formatDate(post.published_at) : formatDate(post.created_at)}
                </span>
                <span className="flex items-center gap-2">
                  <Eye className="w-4 h-4" />
                  {post.view_count} views
                </span>
              </div>

              {/* Share */}
              <div className="flex items-center gap-2 ml-auto">
                <button
                  onClick={shareOnTwitter}
                  className="p-2.5 text-foreground-subtle hover:text-foreground hover:bg-background-secondary rounded-lg transition-all"
                  title="Share on Twitter"
                >
                  <Twitter className="w-4 h-4" />
                </button>
                <button
                  onClick={shareOnLinkedIn}
                  className="p-2.5 text-foreground-subtle hover:text-foreground hover:bg-background-secondary rounded-lg transition-all"
                  title="Share on LinkedIn"
                >
                  <Linkedin className="w-4 h-4" />
                </button>
                <button
                  onClick={handleCopyLink}
                  className="p-2.5 text-foreground-subtle hover:text-foreground hover:bg-background-secondary rounded-lg transition-all"
                  title="Copy link"
                >
                  {copied ? <Check className="w-4 h-4 text-accent" /> : <Copy className="w-4 h-4" />}
                </button>
              </div>
            </div>
          </header>

          {/* Cover Image */}
          {post.cover_image && (
            <div className="relative aspect-[21/9] rounded-2xl overflow-hidden mb-14 bg-background-secondary ring-1 ring-border">
              <Image
                src={post.cover_image}
                alt={post.title}
                fill
                className="object-cover"
                priority
              />
            </div>
          )}

          {/* Content */}
          <div 
            className="prose prose-invert prose-lg max-w-none
              prose-headings:font-display prose-headings:tracking-tight prose-headings:text-foreground
              prose-h2:text-2xl sm:prose-h2:text-3xl prose-h2:mt-14 prose-h2:mb-6
              prose-h3:text-xl sm:prose-h3:text-2xl prose-h3:mt-10 prose-h3:mb-4
              prose-p:text-foreground-muted prose-p:leading-[1.8] prose-p:mb-6
              prose-a:text-accent prose-a:no-underline hover:prose-a:underline prose-a:font-medium
              prose-strong:text-foreground prose-strong:font-semibold
              prose-code:text-accent prose-code:bg-accent/10 prose-code:px-2 prose-code:py-1 prose-code:rounded-md prose-code:text-sm prose-code:font-mono
              prose-pre:bg-background-secondary prose-pre:border prose-pre:border-border prose-pre:rounded-xl
              prose-blockquote:border-l-4 prose-blockquote:border-accent prose-blockquote:bg-accent/5 prose-blockquote:py-4 prose-blockquote:px-8 prose-blockquote:rounded-r-xl prose-blockquote:not-italic prose-blockquote:text-foreground-muted
              prose-ul:text-foreground-muted prose-ol:text-foreground-muted
              prose-li:marker:text-accent prose-li:mb-2
              prose-img:rounded-xl prose-img:ring-1 prose-img:ring-border
            "
            dangerouslySetInnerHTML={{ __html: post.content }}
          />

          {/* Tags */}
          {post.tags.length > 0 && (
            <div className="mt-16 pt-8 border-t border-border">
              <div className="flex items-center gap-3 flex-wrap">
                <Tag className="w-4 h-4 text-foreground-subtle" />
                {post.tags.map((tag) => (
                  <Link
                    key={tag}
                    href={`/blog?tag=${encodeURIComponent(tag)}`}
                    className="px-4 py-2 bg-background-secondary/50 border border-border rounded-full text-sm text-foreground-muted hover:text-accent hover:border-accent/30 transition-all"
                  >
                    {tag}
                  </Link>
                ))}
              </div>
            </div>
          )}

          {/* Author Box */}
          {post.author.name && (
            <div className="mt-16 p-8 bg-background-secondary/50 border border-border rounded-2xl">
              <div className="flex items-start gap-5">
                <div className="w-16 h-16 bg-accent/10 rounded-full flex items-center justify-center flex-shrink-0">
                  <User className="w-8 h-8 text-accent" />
                </div>
                <div>
                  <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-1">Written by</p>
                  <h4 className="text-xl font-display text-foreground mb-2">{post.author.name}</h4>
                  <p className="text-foreground-muted text-sm leading-relaxed">
                    Expert domain hunter sharing insights and strategies to help you find premium domains.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* CTA */}
          <div className="mt-20 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">
              <span className="text-sm font-semibold text-accent uppercase tracking-wider">Ready to Hunt?</span>
              <h3 className="mt-4 text-2xl sm:text-3xl font-display text-foreground mb-4">
                Start finding premium domains today
              </h3>
              <p className="text-foreground-muted mb-8 max-w-xl mx-auto">
                Join thousands of domain hunters using pounce to discover, monitor, and secure valuable domains.
              </p>
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <Link
                  href="/register"
                  className="inline-flex items-center justify-center gap-2 px-8 py-4 bg-accent text-background rounded-xl font-medium hover:bg-accent-hover transition-all"
                >
                  Join the Hunt
                </Link>
                <Link
                  href="/blog"
                  className="inline-flex items-center justify-center gap-2 px-8 py-4 bg-background border border-border rounded-xl font-medium text-foreground hover:border-accent/50 transition-all"
                >
                  More Articles
                </Link>
              </div>
            </div>
          </div>
        </article>
      </main>

      <Footer />
    </div>
  )
}
