import { prisma } from "@/lib/prisma";
import { notFound } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, Flame } from "lucide-react";
import { VideoCard } from "@/components/VideoCard";
import { formatNumber } from "@/lib/utils";
import { getCached, setCached } from "@/lib/memoryCache";

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const metaCacheKey = `cat_meta_${slug}`;
  let title = getCached<string>(metaCacheKey);
  if (!title) {
    const category = await prisma.category.findUnique({ where: { slug }, select: { name: true } });
    if (!category) return {};
    title = `${category.name} – MTBR`;
    setCached(metaCacheKey, title, 3600000);
  }
  return { title };
}

export default async function CategoryPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ page?: string }>;
}) {
  const { slug } = await params;
  const { page: pageParam } = await searchParams;
  const page = Math.max(1, parseInt(pageParam || "1"));
  const PER_PAGE = 24;

  const cacheKey = `cat_slug_${slug}_p_${page}`;
  const cached = getCached<{ category: any; videos: any[]; total: number; totalPages: number }>(cacheKey);

  let category: any = null;
  let videos: any[] = [];
  let total = 0;
  let totalPages = 1;

  if (cached) {
    category = cached.category;
    videos = cached.videos;
    total = cached.total;
    totalPages = cached.totalPages;
  } else {
    category = await prisma.category.findUnique({
      where: { slug },
      select: { id: true, name: true, slug: true },
    });

    if (!category) notFound();

    // Fast indexed count (75ms max on 1M rows, cached 10 minutes)
    const countCacheKey = `cat_count_${category.id}`;
    let catCount = getCached<number>(countCacheKey);
    if (catCount === null || catCount === undefined) {
      const countRes = await prisma.$queryRaw<Array<{ cnt: bigint | number }>>`
        SELECT COUNT(*) as cnt FROM "Media" WHERE "categoryId" = ${category.id} AND "isPublished" = 1 AND "type" = 'VIDEO'
      `.catch(() => null);
      catCount = countRes && countRes[0] ? Number(countRes[0].cnt) : 0;
      setCached(countCacheKey, catCount, 600000); // 10 minutes
    }
    total = catCount;
    totalPages = Math.max(1, Math.ceil(total / PER_PAGE));

    // Ultra-fast indexed videos query (0.38ms via idx_media_cat_pub_views)
    videos = await prisma.media.findMany({
      where: { categoryId: category.id, isPublished: true, type: "VIDEO" },
      orderBy: { views: "desc" },
      skip: (page - 1) * PER_PAGE,
      take: PER_PAGE,
      select: {
        id: true,
        title: true,
        titleFr: true,
        thumbnailUrl: true,
        duration: true,
        views: true,
        isPremium: true,
        
        createdAt: true,
        uploader: { select: { id: true, name: true, image: true, isVerified: true } },
      },
    });

    setCached(cacheKey, { category, videos, total, totalPages }, 60000);
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header */}
      <Link
        href="/categories"
        prefetch={true}
        className="inline-flex items-center gap-2 text-sm text-[#aaaaaa] hover:text-white transition-colors mb-6"
      >
        <ArrowLeft size={16} /> Toutes les catégories
      </Link>

      <div className="flex items-center justify-between mb-8 flex-wrap gap-4">
        <div>
          <h1 className="text-3xl font-black text-white flex items-center gap-3">
            <Flame className="text-[#e05a68]" />
            {category.name}
          </h1>
          <p className="text-[#aaaaaa] text-sm mt-1">
            {formatNumber(total)} vidéos
            {totalPages > 1 && ` · Page ${page} / ${totalPages}`}
          </p>
        </div>
      </div>

      {/* Grid */}
      {videos.length > 0 ? (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-x-3 gap-y-7">
        {videos.map((media) => (
          <VideoCard key={media.id} media={media} />
        ))}
      </div>
      ) : (
        <div className="py-24 text-center text-[#aaaaaa]">
          Aucune vidéo dans cette catégorie pour l'instant.
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2 mt-12 flex-wrap">
          {page > 1 && (
            <Link
              href={`/categories/${slug}?page=${page - 1}`}
              prefetch={true}
              className="px-4 py-2 rounded-lg bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68] text-sm font-bold text-[#d8cbd0] hover:text-white transition-colors"
            >
              ← Précédent
            </Link>
          )}

          {Array.from({ length: Math.min(7, totalPages) }, (_, i) => {
            const p = page <= 4
              ? i + 1
              : page >= totalPages - 3
              ? totalPages - 6 + i
              : page - 3 + i;
            if (p < 1 || p > totalPages) return null;
            return (
              <Link
                key={p}
                href={`/categories/${slug}?page=${p}`}
                prefetch={true}
                className={`w-10 h-10 flex items-center justify-center rounded-lg text-sm font-bold transition-all ${
                  p === page
                    ? "bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white border border-[#e05a68] shadow-[0_0_15px_rgba(224,90,104,0.35)]"
                    : "bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68] text-[#d8cbd0] hover:text-white"
                }`}
              >
                {p}
              </Link>
            );
          })}

          {page < totalPages && (
            <Link
              href={`/categories/${slug}?page=${page + 1}`}
              prefetch={true}
              className="px-4 py-2 rounded-lg bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68] text-sm font-bold text-[#d8cbd0] hover:text-white transition-colors"
            >
              Suivant →
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
