'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,
  Twitter,
  Linkedin,
  Copy,
  Check,
} from 'lucide-react'
import type { BlogPost } from './types'

export default function BlogPostClient({ initialPost }: { initialPost: BlogPost }) {
  const params = useParams()
  const slug = params.slug as string

  const [post, setPost] = useState<BlogPost | null>(initialPost)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    if (!slug) return
    // Always load the full post once to render content and to increment view_count server-side.
    // If initialPost already includes content (future-proof), we still refresh once for up-to-date view_count.
    void loadPost()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [slug])

  const loadPost = async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await api.getBlogPost(slug)
      setPost(data)
    } catch {
      setError('Blog post not found')
      setPost(null)
    } 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">
        <Header />
        <main className="flex-1 flex items-center justify-center px-4">
          <div className="text-center max-w-md">
            <h1 className="text-2xl font-bold text-foreground mb-2">Article not found</h1>
            <p className="text-foreground-muted mb-6">This post may have been removed or is not published.</p>
            <Link href="/blog" className="inline-flex items-center gap-2 text-accent hover:underline">
              <ArrowLeft className="w-4 h-4" />
              Back to Blog
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    )
  }

  const content = post.content || ''

  return (
    <div className="min-h-screen bg-background relative overflow-hidden flex flex-col">
      <Header />

      <main className="flex-1 pt-28 pb-16 px-4 sm:px-6">
        <div className="max-w-4xl mx-auto">
          <Link href="/blog" className="inline-flex items-center gap-2 text-foreground-muted hover:text-foreground transition-colors mb-8">
            <ArrowLeft className="w-4 h-4" />
            Back to Blog
          </Link>

          <article>
            <header className="mb-10">
              <h1 className="text-4xl sm:text-5xl font-bold text-foreground mb-4 leading-tight">{post.title}</h1>
              {post.excerpt ? <p className="text-lg text-foreground-muted">{post.excerpt}</p> : null}

              <div className="flex flex-wrap items-center gap-4 text-sm text-foreground-muted mt-6">
                {post.published_at ? (
                  <span className="inline-flex items-center gap-2">
                    <Calendar className="w-4 h-4" />
                    {formatDate(post.published_at)}
                  </span>
                ) : null}
                {content ? (
                  <span className="inline-flex items-center gap-2">
                    <Clock className="w-4 h-4" />
                    {estimateReadTime(content)}
                  </span>
                ) : null}
                <span className="inline-flex items-center gap-2">
                  <Eye className="w-4 h-4" />
                  {post.view_count.toLocaleString()}
                </span>
              </div>

              {post.cover_image ? (
                <div className="mt-8 relative aspect-[16/9] rounded-2xl overflow-hidden border border-white/10">
                  <Image src={post.cover_image} alt={post.title} fill className="object-cover" />
                </div>
              ) : null}
            </header>

            <div className="prose prose-invert max-w-none">
              {/* backend already sanitizes; we render trusted HTML */}
              <div dangerouslySetInnerHTML={{ __html: content }} />
            </div>

            <footer className="mt-12 pt-8 border-t border-white/10">
              {post.tags?.length ? (
                <div className="flex flex-wrap gap-2 mb-6">
                  {post.tags.map(t => (
                    <span key={t} className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-white/5 border border-white/10 text-xs text-foreground-muted">
                      <Tag className="w-3 h-3" />
                      {t}
                    </span>
                  ))}
                </div>
              ) : null}

              <div className="flex flex-wrap items-center gap-3">
                <button
                  onClick={shareOnTwitter}
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-white/5 border border-white/10 text-sm hover:bg-white/10 transition-colors"
                >
                  <Twitter className="w-4 h-4" />
                  Share
                </button>
                <button
                  onClick={shareOnLinkedIn}
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-white/5 border border-white/10 text-sm hover:bg-white/10 transition-colors"
                >
                  <Linkedin className="w-4 h-4" />
                  LinkedIn
                </button>
                <button
                  onClick={handleCopyLink}
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-white/5 border border-white/10 text-sm hover:bg-white/10 transition-colors"
                >
                  {copied ? <Check className="w-4 h-4 text-accent" /> : <Copy className="w-4 h-4" />}
                  {copied ? 'Copied' : 'Copy link'}
                </button>
              </div>
            </footer>
          </article>
        </div>
      </main>

      <Footer />
    </div>
  )
}

