import Link from "next/link";
import { notFound } from "next/navigation";
import { templateService } from "@/modules/templates";
import { AdminPageHeader } from "@/components/admin/AdminBreadcrumbs";
import { StatusBadge } from "@/components/admin/StatusBadge";
import { formatDate, pluralize } from "@/lib/client-api";
import { Button } from "@/components/ui/button";
import { TemplateDeleteControl } from "./template-delete-control";

export const dynamic = "force-dynamic";
export const metadata = { title: "Template details · Admin" };

export default async function TemplateDetailPage({
  params,
}: {
  params: Promise<{ templateId: string }>;
}) {
  const { templateId } = await params;
  const template = await templateService.findById(templateId);
  if (!template) notFound();
  const enabled = template.modules.filter((m) => m.enabled);
  return (
    <div className="space-y-6">
      <AdminPageHeader
        breadcrumbs={[
          { label: "Admin", href: "/admin" },
          { label: "Templates", href: "/admin/templates" },
          { label: template.name },
        ]}
        title={template.name}
        description={template.description}
        actions={
          <div className="flex items-center gap-2">
            <Link href={`/admin/templates/${template.id}/edit`}>
              <Button size="sm">Edit template</Button>
            </Link>
            <TemplateDeleteControl
              templateId={template.id}
              templateName={template.name}
            />
          </div>
        }
      />
      <div className="grid gap-6 lg:grid-cols-3">
        <section className="rounded-2xl border border-border bg-surface p-5 shadow-sm lg:col-span-2">
          <h2 className="text-sm font-semibold text-foreground">Overview</h2>
          <dl className="mt-4 grid gap-3 sm:grid-cols-2 text-sm">
            <div>
              <dt className="text-xs text-muted">Status</dt>
              <dd>
                <StatusBadge status={template.status} />
              </dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Version</dt>
              <dd className="font-medium">v{template.version}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Category</dt>
              <dd className="font-medium capitalize">{template.category}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Slug</dt>
              <dd className="font-mono text-xs">{template.slug}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Created</dt>
              <dd>{formatDate(template.createdAt)}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Updated</dt>
              <dd>{formatDate(template.updatedAt)}</dd>
            </div>
          </dl>
        </section>
        <section className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <h2 className="text-sm font-semibold text-foreground">Settings</h2>
          <ul className="mt-3 space-y-1 text-sm">
            {Object.entries(template.settings).map(([k, v]) => (
              <li key={k} className="flex items-center justify-between">
                <span className="text-muted">{k.replace(/([A-Z])/g, " $1").toLowerCase()}</span>
                <span className={v ? "text-green-700" : "text-muted"}>
                  {v ? "Yes" : "No"}
                </span>
              </li>
            ))}
          </ul>
        </section>
      </div>
      <section className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
        <h2 className="text-sm font-semibold text-foreground">
          Modules ({pluralize(enabled.length, "enabled")} of {template.modules.length})
        </h2>
        {template.modules.length === 0 ? (
          <p className="mt-2 text-sm text-muted">No modules attached.</p>
        ) : (
          <ul className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
            {template.modules.map((m) => (
              <li
                key={String(m.moduleId)}
                className="rounded-xl border border-border bg-surface p-3"
              >
                <p className="font-medium">{m.name}</p>
                <p className="text-xs text-muted capitalize">
                  {m.category} · {m.isRequired ? "Required" : "Optional"}
                </p>
                <p className="mt-1 text-xs text-muted">
                  {m.enabled ? "Enabled" : "Disabled"}
                </p>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}