import { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Helmet } from 'react-helmet-async'
import { posts as postsAPI } from '../utils/api'
import { generateJsonLd } from '../utils/seo'
import BlockRenderer from '../components/BlockRenderer'
import { Clock, Eye } from 'lucide-react'

export default function PostPage() {
  const { categorySlug, postSlug } = useParams()
  const [post, setPost] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchPost = async () => {
      try {
        const { data } = await postsAPI.getBySlug(categorySlug, postSlug)
        setPost(data)
      } catch (err) {
        console.error('Failed to fetch post:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchPost()
  }, [categorySlug, postSlug])

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    )
  }

  if (!post) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <p className="text-gray-500 text-lg">Post not found.</p>
      </div>
    )
  }

  const siteUrl = window.location.origin
  const jsonLd = generateJsonLd(post, siteUrl)

  return (
    <>
      <Helmet>
        <title>{post.seo_title || post.title} - CardingCentral</title>
        <meta name="description" content={post.seo_description || post.excerpt} />
        <meta name="keywords" content={post.seo_keywords} />
        <link rel="canonical" href={`${siteUrl}/${categorySlug}/${postSlug}`} />

        {/* OG Tags */}
        <meta property="og:title" content={post.seo_title || post.title} />
        <meta property="og:description" content={post.seo_description || post.excerpt} />
        {post.og_image && <meta property="og:image" content={`${siteUrl}${post.og_image}`} />}
        <meta property="og:url" content={`${siteUrl}/${categorySlug}/${postSlug}`} />
        <meta property="og:type" content="article" />

        {/* Twitter Card */}
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content={post.seo_title || post.title} />
        <meta name="twitter:description" content={post.seo_description || post.excerpt} />
        {post.og_image && <meta name="twitter:image" content={`${siteUrl}${post.og_image}`} />}

        {/* JSON-LD */}
        <script type="application/ld+json">{JSON.stringify(jsonLd)}</script>
      </Helmet>

      {/* Banner Image */}
      {post.banner_image && (
        <div className="w-full h-96 overflow-hidden bg-gray-200">
          <img
            src={`/uploads/${post.banner_image}`}
            alt={post.title}
            className="w-full h-full object-cover"
          />
        </div>
      )}

      {/* Article Content */}
      <article className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Header */}
        <div className="mb-8 pb-8 border-b border-gray-200">
          <div className="mb-4">
            <span className="inline-block px-4 py-1 bg-blue-100 text-blue-700 text-sm font-semibold rounded-full">
              {post.category_name}
            </span>
          </div>
          <h1 className="text-5xl font-bold text-gray-900 mb-4">{post.title}</h1>
          <p className="text-xl text-gray-600 mb-6">{post.excerpt}</p>
          <div className="flex flex-wrap items-center gap-6 text-gray-600">
            <div className="flex items-center gap-2">
              <Clock size={18} />
              <span>{post.reading_time || 5} min read</span>
            </div>
            <div className="flex items-center gap-2">
              <Eye size={18} />
              <span>{post.view_count} views</span>
            </div>
            {post.published_at && (
              <time dateTime={post.published_at} className="text-sm">
                {new Date(post.published_at).toLocaleDateString('en-US', {
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                })}
              </time>
            )}
          </div>
        </div>

        {/* Content Blocks */}
        <div className="prose prose-lg max-w-none">
          {post.content && Array.isArray(post.content) ? (
            post.content.map((block, i) => (
              <BlockRenderer key={i} block={block} index={i} />
            ))
          ) : (
            <p className="text-gray-600">No content available.</p>
          )}
        </div>

        {/* Tags */}
        {post.seo_keywords && (
          <div className="mt-12 pt-8 border-t border-gray-200">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Tags</h3>
            <div className="flex flex-wrap gap-3">
              {post.seo_keywords.split(',').map((tag, i) => (
                <span key={i} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm">
                  #{tag.trim()}
                </span>
              ))}
            </div>
          </div>
        )}
      </article>
    </>
  )
}
