import { prisma } from "@/lib/db";
import { AddonCard } from "@/components/public/AddonCard";
import { Badge } from "@/components/ui/badge";
import Link from "next/link";

const categoryLabels: Record<string, string> = {
  general: "通用",
  gameplay: "游戏玩法",
  ui: "界面增强",
  combat: "战斗",
  raid: "团队副本",
  pvp: "PvP",
  tradeskill: "专业技能",
  utility: "实用工具",
};

export const metadata = {
  title: "插件列表 - Nanami",
};

export const dynamic = "force-dynamic";

export default async function AddonsPage({
  searchParams,
}: {
  searchParams: Promise<{ category?: string; search?: string }>;
}) {
  const { category, search } = await searchParams;

  const where: Record<string, unknown> = { published: true };
  if (category) where.category = category;
  if (search) {
    where.OR = [
      { name: { contains: search, mode: "insensitive" } },
      { summary: { contains: search, mode: "insensitive" } },
    ];
  }

  const addons = await prisma.addon.findMany({
    where,
    include: {
      releases: {
        where: { isLatest: true },
        select: { version: true },
      },
    },
    orderBy: { totalDownloads: "desc" },
  });

  const categories = await prisma.addon.groupBy({
    by: ["category"],
    where: { published: true },
    _count: { id: true },
  });

  return (
    <div className="mx-auto max-w-6xl px-4 py-12">
      <h1 className="text-3xl font-bold">插件列表</h1>
      <p className="mt-2 text-muted-foreground">
        浏览和下载 World of Warcraft 插件
      </p>

      {/* Category Filter */}
      <div className="mt-6 flex flex-wrap gap-2">
        <Link href="/addons">
          <Badge
            variant={!category ? "default" : "outline"}
            className="cursor-pointer"
          >
            全部
          </Badge>
        </Link>
        {categories.map((cat) => (
          <Link key={cat.category} href={`/addons?category=${cat.category}`}>
            <Badge
              variant={category === cat.category ? "default" : "outline"}
              className="cursor-pointer"
            >
              {categoryLabels[cat.category] || cat.category} ({cat._count.id})
            </Badge>
          </Link>
        ))}
      </div>

      {/* Addon Grid */}
      <div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
        {addons.map((addon) => (
          <AddonCard key={addon.id} addon={addon} />
        ))}
      </div>

      {addons.length === 0 && (
        <div className="mt-16 text-center">
          <p className="text-lg text-muted-foreground">
            {search ? `没有找到"${search}"相关的插件` : "暂无插件"}
          </p>
        </div>
      )}
    </div>
  );
}
