import React from 'react';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import dbConnect from '@/lib/db';
import Post from '@/models/Post';
import Category from '@/models/Category';
import { notFound } from 'next/navigation';
import { Calendar, ArrowRight } from 'lucide-react';
import Link from 'next/link';

export const revalidate = 60;

async function getCategoryPosts(slug: string) {
  try {
    await dbConnect();
    
    // Find category to get correct display name if needed, but slug query on posts is enough
    const category = await (Category as any).findOne({ slug });
    
    // Find posts with this category slug
    const posts = await (Post as any).find({ 
      status: 'published',
      categories: slug 
    }).sort({ createdAt: -1 });

    return { 
      categoryName: category ? category.name : slug.replace('-', ' '),
      posts: JSON.parse(JSON.stringify(posts)) 
    };
  } catch (e) {
    return { categoryName: slug, posts: [] };
  }
}

export default async function CategoryPage(props: { params: Promise<{ slug: string }> }) {
  const params = await props.params;
  const { categoryName, posts } = await getCategoryPosts(params.slug);

  if (!posts && posts.length === 0) {
      // Option: return notFound() if strictly required, but showing empty state is often better
  }

  return (
    <div className="min-h-screen flex flex-col">
      <Navbar />
      
      <main className="flex-grow bg-slate-50 dark:bg-slate-900 py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h1 className="text-4xl font-bold text-slate-900 dark:text-white capitalize font-display mb-4">{categoryName}</h1>
            <div className="w-16 h-1 bg-primary mx-auto"></div>
          </div>

          {posts.length === 0 ? (
            <div className="text-center py-20 text-slate-500">
              <p>No posts found in this category yet.</p>
            </div>
          ) : (
            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
              {posts.map((post: any) => (
                <article key={post._id} className="bg-white dark:bg-slate-800 rounded-xl overflow-hidden shadow-md hover:shadow-xl transition duration-300 flex flex-col">
                  <div className="h-48 overflow-hidden relative">
                    <img 
                      src={post.featuredImage || 'https://via.placeholder.com/600x400?text=No+Image'} 
                      alt={post.title} 
                      className="w-full h-full object-cover hover:scale-105 transition duration-500"
                    />
                  </div>
                  <div className="p-6 flex-1 flex flex-col">
                    <div className="flex items-center gap-2 text-xs text-slate-500 mb-3">
                      <Calendar size={14} />
                      {new Date(post.createdAt).toLocaleDateString()}
                    </div>
                    <h2 className="text-xl font-bold text-slate-900 dark:text-white mb-3 line-clamp-2">{post.title}</h2>
                    <p className="text-slate-600 dark:text-slate-400 text-sm mb-4 line-clamp-3 flex-1">{post.excerpt}</p>
                    <Link href={`/post/${post.slug}`} className="text-primary font-semibold text-sm flex items-center gap-1 hover:gap-2 transition-all">
                      Read More <ArrowRight size={16} />
                    </Link>
                  </div>
                </article>
              ))}
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  );
}