import { prisma } from "@/lib/db";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Package, Download, FileUp } from "lucide-react";

export const dynamic = "force-dynamic";

export default async function DashboardPage() {
  const [addonCount, totalDownloads, releaseCount, recentReleases] =
    await Promise.all([
      prisma.addon.count(),
      prisma.addon.aggregate({ _sum: { totalDownloads: true } }),
      prisma.release.count(),
      prisma.release.findMany({
        take: 5,
        orderBy: { createdAt: "desc" },
        include: { addon: { select: { name: true } } },
      }),
    ]);

  const stats = [
    {
      title: "插件总数",
      value: addonCount,
      icon: Package,
    },
    {
      title: "总下载量",
      value: totalDownloads._sum.totalDownloads || 0,
      icon: Download,
    },
    {
      title: "版本发布数",
      value: releaseCount,
      icon: FileUp,
    },
  ];

  return (
    <div className="space-y-8">
      <h1 className="text-3xl font-bold">仪表盘</h1>

      <div className="grid gap-4 md:grid-cols-3">
        {stats.map((stat) => (
          <Card key={stat.title}>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {stat.title}
              </CardTitle>
              <stat.icon className="h-5 w-5 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold">{stat.value}</div>
            </CardContent>
          </Card>
        ))}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>最近发布</CardTitle>
          <CardDescription>最近发布的版本更新</CardDescription>
        </CardHeader>
        <CardContent>
          {recentReleases.length === 0 ? (
            <p className="text-sm text-muted-foreground">暂无发布记录</p>
          ) : (
            <div className="space-y-4">
              {recentReleases.map((release) => (
                <div
                  key={release.id}
                  className="flex items-center justify-between border-b pb-3 last:border-0"
                >
                  <div>
                    <p className="font-medium">{release.addon.name}</p>
                    <p className="text-sm text-muted-foreground">
                      v{release.version}
                      {release.gameVersion &&
                        ` · WoW ${release.gameVersion}`}
                    </p>
                  </div>
                  <div className="text-right text-sm text-muted-foreground">
                    <p>{release.downloadCount} 次下载</p>
                    <p>{new Date(release.createdAt).toLocaleDateString("zh-CN")}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
