import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { ContentCard } from "@/components/site/ContentCard";
import { VideoCard } from "@/components/site/VideoCard";
import { prisma } from "@/lib/prisma";
import { siteUrl } from "@/lib/utils";

type PageProps = {
  params: Promise<{ slug: string }>;
};

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const category = await prisma.category.findUnique({ where: { slug } });

  if (!category) {
    return {};
  }

  return {
    title: category.name,
    description: category.description ?? `Explore ${category.name} on Just Chill Nepal.`,
    alternates: { canonical: siteUrl(`/categories/${category.slug}`) }
  };
}

export default async function CategoryDetailPage({ params }: PageProps) {
  const { slug } = await params;
  const category = await prisma.category.findUnique({
    where: { slug },
    include: {
      posts: {
        where: { approvalStatus: "APPROVED", status: "PUBLISHED" },
        orderBy: { publishedAt: "desc" }
      },
      videos: {
        where: { approvalStatus: "APPROVED", status: "PUBLISHED" },
        orderBy: { publishedAt: "desc" }
      }
    }
  });

  if (!category) {
    notFound();
  }

  return (
    <main className="container" style={{ padding: "4rem 1.25rem" }}>
      <div className="section-head">
        <div>
          <span className="pill">Category</span>
          <h1 className="section-title">{category.name}</h1>
          <p className="muted">{category.description}</p>
        </div>
      </div>

      <h2>Videos</h2>
      <div className="youtube-grid">
        {category.videos.map((video) => (
          <VideoCard
            category={category.name}
            date={video.publishedAt}
            description={video.description}
            href={`/videos/${video.slug}`}
            key={video.id}
            thumbnail={video.thumbnail}
            title={video.title}
            youtubeId={video.youtubeId}
          />
        ))}
      </div>

      <h2 style={{ marginTop: "3rem" }}>Articles</h2>
      <div className="grid-cards">
        {category.posts.map((post) => (
          <ContentCard
            date={post.publishedAt}
            excerpt={post.excerpt}
            href={`/articles/${post.slug}`}
            key={post.id}
            title={post.title}
          />
        ))}
      </div>
    </main>
  );
}
