import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Download, Package, Calendar, Tag } from "lucide-react";
import { DownloadButton } from "@/components/public/DownloadButton";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const addon = await prisma.addon.findUnique({
    where: { slug },
    select: { name: true, summary: true },
  });
  if (!addon) return { title: "Not Found" };
  return {
    title: `${addon.name} - Nanami`,
    description: addon.summary,
  };
}

export const dynamic = "force-dynamic";

export default async function AddonDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const addon = await prisma.addon.findUnique({
    where: { slug },
    include: {
      releases: { orderBy: { createdAt: "desc" } },
      screenshots: { orderBy: { sortOrder: "asc" } },
    },
  });

  if (!addon || !addon.published) notFound();

  const latestRelease = addon.releases.find((r) => r.isLatest);

  return (
    <div className="mx-auto max-w-6xl px-4 py-12">
      {/* Header */}
      <div className="flex flex-col gap-6 sm:flex-row sm:items-start">
        {addon.iconUrl ? (
          <img
            src={addon.iconUrl}
            alt={addon.name}
            className="h-20 w-20 rounded-2xl object-cover"
          />
        ) : (
          <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-primary/10">
            <Package className="h-10 w-10 text-primary" />
          </div>
        )}
        <div className="flex-1">
          <h1 className="text-3xl font-bold">{addon.name}</h1>
          <p className="mt-2 text-lg text-muted-foreground">{addon.summary}</p>
          <div className="mt-3 flex flex-wrap items-center gap-3">
            <Badge>{addon.category}</Badge>
            <span className="flex items-center gap-1 text-sm text-muted-foreground">
              <Download className="h-3.5 w-3.5" />
              {addon.totalDownloads.toLocaleString()} 次下载
            </span>
            {latestRelease && (
              <span className="flex items-center gap-1 text-sm text-muted-foreground">
                <Tag className="h-3.5 w-3.5" />
                v{latestRelease.version}
              </span>
            )}
          </div>
        </div>
        {latestRelease && (
          <div className="shrink-0">
            <DownloadButton
              releaseId={latestRelease.id}
              version={latestRelease.version}
              size="lg"
            />
          </div>
        )}
      </div>

      <Separator className="my-8" />

      <div className="grid gap-8 lg:grid-cols-3">
        {/* Description */}
        <div className="lg:col-span-2">
          <Card>
            <CardHeader>
              <CardTitle>介绍</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="prose prose-neutral max-w-none dark:prose-invert">
                <MarkdownContent content={addon.description} />
              </div>
            </CardContent>
          </Card>

          {/* Screenshots */}
          {addon.screenshots.length > 0 && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle>截图</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid gap-4 sm:grid-cols-2">
                  {addon.screenshots.map((ss) => (
                    <img
                      key={ss.id}
                      src={ss.imageUrl}
                      alt="Screenshot"
                      className="rounded-lg border object-cover"
                    />
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>

        {/* Sidebar - Releases */}
        <div>
          <Card>
            <CardHeader>
              <CardTitle>版本历史</CardTitle>
              <CardDescription>
                共 {addon.releases.length} 个版本
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {addon.releases.map((release) => (
                <div
                  key={release.id}
                  className="rounded-lg border p-4 transition-colors hover:bg-muted/50"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="font-semibold">v{release.version}</span>
                      {release.isLatest && (
                        <Badge variant="default" className="text-xs">
                          最新
                        </Badge>
                      )}
                    </div>
                    <DownloadButton
                      releaseId={release.id}
                      version={release.version}
                      size="sm"
                    />
                  </div>
                  {release.gameVersion && (
                    <p className="mt-1 text-xs text-muted-foreground">
                      WoW {release.gameVersion}
                    </p>
                  )}
                  <div className="mt-2 flex items-center gap-3 text-xs text-muted-foreground">
                    <span className="flex items-center gap-1">
                      <Calendar className="h-3 w-3" />
                      {new Date(release.createdAt).toLocaleDateString("zh-CN")}
                    </span>
                    <span className="flex items-center gap-1">
                      <Download className="h-3 w-3" />
                      {release.downloadCount}
                    </span>
                  </div>
                  {release.changelog && (
                    <p className="mt-2 text-sm text-muted-foreground whitespace-pre-line">
                      {release.changelog}
                    </p>
                  )}
                </div>
              ))}
              {addon.releases.length === 0 && (
                <p className="text-sm text-muted-foreground">暂无版本发布</p>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

function MarkdownContent({ content }: { content: string }) {
  const html = content
    .replace(/^### (.*$)/gm, '<h3 class="text-lg font-semibold mt-4 mb-2">$1</h3>')
    .replace(/^## (.*$)/gm, '<h2 class="text-xl font-semibold mt-6 mb-3">$1</h2>')
    .replace(/^# (.*$)/gm, '<h1 class="text-2xl font-bold mt-6 mb-3">$1</h1>')
    .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
    .replace(/\*(.*?)\*/g, "<em>$1</em>")
    .replace(/`(.*?)`/g, '<code class="rounded bg-muted px-1.5 py-0.5 text-sm">$1</code>')
    .replace(/^- (.*$)/gm, '<li class="ml-4 list-disc">$1</li>')
    .replace(/\n\n/g, '<br/><br/>')
    .replace(/\n/g, "<br/>");

  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
