import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import { Helmet } from 'react-helmet-async'
import { posts as postsAPI, categories as categoriesAPI } from '../utils/api'
import { motion } from 'framer-motion'

export default function CategoryPage() {
  const { categorySlug } = useParams()
  const [posts, setPosts] = useState([])
  const [category, setCategory] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [postsRes, catRes] = await Promise.all([
          postsAPI.getAll({ category: categorySlug, limit: 50 }),
          categoriesAPI.getBySlug(categorySlug),
        ])
        setPosts(postsRes.data)
        setCategory(catRes.data)
      } catch (err) {
        console.error('Failed to fetch category data:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchData()
  }, [categorySlug])

  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 (!category) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <p className="text-gray-500 text-lg">Category not found.</p>
      </div>
    )
  }

  return (
    <>
      <Helmet>
        <title>{category.seo_title || category.name} - CardingCentral</title>
        <meta name="description" content={category.seo_description || category.description} />
        <link rel="canonical" href={`https://cardingcentral.com/${categorySlug}`} />
      </Helmet>

      {/* Category Header */}
      <section className={`bg-gradient-to-r from-blue-600 to-blue-800 text-white py-12`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <h1 className="text-4xl font-bold mb-4">{category.name}</h1>
          <p className="text-blue-100 text-lg">{category.description}</p>
        </div>
      </section>

      {/* Posts */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        {posts.length > 0 ? (
          <div className="space-y-6">
            {posts.map((post, i) => (
              <motion.article
                key={post.id}
                className="bg-white rounded-lg shadow-md hover:shadow-xl transition overflow-hidden flex flex-col md:flex-row"
                whileHover={{ y: -2 }}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: i * 0.1 }}
              >
                {post.thumbnail_image && (
                  <div className="md:w-48 flex-shrink-0">
                    <img
                      src={`/uploads/${post.thumbnail_image}`}
                      alt={post.title}
                      className="w-full h-full object-cover"
                    />
                  </div>
                )}
                <div className="p-6 flex-1">
                  <Link to={`/${categorySlug}/${post.slug}`}>
                    <h2 className="text-2xl font-bold text-gray-900 mb-2 hover:text-blue-600 transition">
                      {post.title}
                    </h2>
                  </Link>
                  <p className="text-gray-600 mb-4">{post.excerpt}</p>
                  <div className="flex items-center justify-between text-sm text-gray-500">
                    <span>📖 {post.reading_time || 5} min read</span>
                    <span>👁️ {post.view_count || 0} views</span>
                  </div>
                </div>
              </motion.article>
            ))}
          </div>
        ) : (
          <p className="text-center text-gray-500 py-12">No posts in this category yet.</p>
        )}
      </section>
    </>
  )
}
