import type { Metadata } from "next";
import Link from "next/link";
import { ArrowRight, Mail } from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import {
  AdminHeading,
  FormSection,
  formatAdminDateTime,
} from "@/components/admin";
import { listTemplates } from "@/lib/email/templates-db";

export const metadata: Metadata = { title: "Email templates" };
export const dynamic = "force-dynamic";

export default async function AdminEmailTemplatesPage() {
  await requireAdmin();
  const templates = await listTemplates();
  return (
    <>
      <AdminHeading
        eyebrow="System"
        title="Email templates"
        lede="Subject and body for every transactional email the site sends. Variables use the {{name}} placeholder syntax."
      />
      <div className="grid gap-4">
        {templates.map((t) => {
          const isCustomised = t.updatedAt.getTime() > 0;
          return (
            <FormSection
              key={t.slug}
              title={t.name}
              description={t.description || t.slug}
              actions={
                <Link
                  href={`/admin/email-templates/${t.slug}`}
                  className="inline-flex items-center gap-1 rounded-lg bg-[var(--color-blue)] px-3 py-1.5 text-[13px] font-semibold text-white hover:opacity-90"
                >
                  Edit
                  <ArrowRight className="h-3.5 w-3.5" aria-hidden />
                </Link>
              }
            >
              <div className="flex flex-wrap items-center gap-4 text-[13px] text-[var(--color-slate)]">
                <span className="inline-flex items-center gap-1.5">
                  <Mail className="h-4 w-4" aria-hidden />
                  <span className="font-mono text-[12px]">{t.slug}</span>
                </span>
                <span>
                  <strong className="text-[var(--color-ink)]">Subject:</strong>{" "}
                  {t.subject}
                </span>
                <span>
                  <strong className="text-[var(--color-ink)]">Variables:</strong>{" "}
                  {t.variables.length === 0
                    ? "—"
                    : t.variables.map((v) => `{{${v}}}`).join(" ")}
                </span>
                {isCustomised && (
                  <span>
                    <strong className="text-[var(--color-ink)]">Updated:</strong>{" "}
                    {formatAdminDateTime(t.updatedAt)}
                  </span>
                )}
              </div>
            </FormSection>
          );
        })}
      </div>
    </>
  );
}
