import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Header } from '../components/Header'
import { Footer } from '../components/Footer'
import { Posts } from '../clientsdk/sdk.gen'
import { createClient } from '../clientsdk/client'
import { customQuerySerializer } from '../clientsdk/querySerializer'
import { TENANT_SLUG, TENANT_API_KEY, API_URL } from '../config'
import { usePageTitle } from '../hooks/usePageTitle'

const client = createClient({
  baseUrl: API_URL,
  querySerializer: customQuerySerializer,
  headers: {
    'X-Tenant-Slug': TENANT_SLUG,
    'X-API-Key': TENANT_API_KEY,
  },
})

export const PostDetail: React.FC = () => {
  const { slug } = useParams<{ slug: string }>()
  usePageTitle('文章详情')
  const [post, setPost] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!slug) return

    const fetchPost = async () => {
      try {
        setLoading(true)
        setError(null)
        
        // Use listPosts with where filter since findPostById doesn't support slug lookup
        const response = await Posts.listPosts({
          client,
          query: {
            where: {
              slug: {
                equals: slug,
              },
            },
            limit: 1,
          },
        })

        const docs = (response as any)?.data?.docs || []
        setPost(docs[0] || null)
      } catch (err) {
        setError(err instanceof Error ? err.message : '加载失败')
        console.error('获取文章失败:', err)
      } finally {
        setLoading(false)
      }
    }

    fetchPost()
  }, [slug])

  const getCategoryTitle = (p: any): string | undefined => {
    // categories is an array, get the first one
    return p?.categories?.[0]?.title
  }

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

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Header />
        <main className="container mx-auto px-4 py-8">
          <div className="animate-pulse">
            <div className="h-8 bg-gray-200 rounded w-1/2 mb-4"></div>
            <div className="h-4 bg-gray-200 rounded w-1/4 mb-6"></div>
            <div className="space-y-3">
              <div className="h-4 bg-gray-200 rounded"></div>
              <div className="h-4 bg-gray-200 rounded"></div>
              <div className="h-4 bg-gray-200 rounded w-3/4"></div>
            </div>
          </div>
        </main>
        <Footer />
      </div>
    )
  }

  if (error || !post) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Header />
        <main className="container mx-auto px-4 py-8">
          <div className="text-center py-12">
            <p className="text-red-600 text-lg">{error || '文章不存在'}</p>
            <button
              onClick={() => window.location.href = '/'}
              className="mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              返回首页
            </button>
          </div>
        </main>
        <Footer />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />

      <main className="container mx-auto px-4 py-8 max-w-4xl">
        <article>
          <header className="mb-8">
            {getCategoryTitle(post) && (
              <span className="inline-block px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm mb-4">
                {getCategoryTitle(post)}
              </span>
            )}
            <h1 className="text-4xl font-bold text-gray-900 mb-4">{post.title}</h1>
            <div className="flex items-center text-gray-600 text-sm">
              <span>{formatDate(post.createdAt)}</span>
            </div>
          </header>

          {post.heroImage && (
            <img
              src={post.heroImage.url}
              alt={post.heroImage.alt || post.title}
              className="w-full h-auto rounded-lg mb-8"
            />
          )}

          <div
            className="prose prose-lg max-w-none"
            dangerouslySetInnerHTML={{ __html: post.content_html || '' }}
          />

          <div className="mt-12 pt-8 border-t border-gray-200">
            <button
              onClick={() => window.location.href = '/'}
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
            >
              返回首页
            </button>
          </div>
        </article>
      </main>

      <Footer />
    </div>
  )
}
