import Link from "next/link";
import { requireSuperAdmin } from "@/lib/auth";
import { db } from "@/lib/db";
import { Badge, btn, Card, Field, PageHeader, input } from "@/components/ui";
import { fmtDateTime } from "@/lib/utils";
import { EMAIL_TEMPLATES, renderTemplate, templateDef } from "@/lib/email-templates";
import { resetEmailTemplate, saveEmailTemplate, testEmailTemplate } from "../actions";

export const metadata = { title: "Email templates" };

export default async function EmailTemplatesPage({
  searchParams,
}: {
  searchParams: Promise<{ key?: string; saved?: string; error?: string; test?: string }>;
}) {
  await requireSuperAdmin();
  const sp = await searchParams;
  const overrides = await db.emailTemplate.findMany();
  const overrideFor = (key: string) => overrides.find((o) => o.key === key);

  const activeKey = sp.key && templateDef(sp.key) ? sp.key : null;
  const def = activeKey ? templateDef(activeKey)! : null;
  const override = activeKey ? overrideFor(activeKey) : null;
  const preview = def ? await renderTemplate(def.key, def.variables, { title: "Preview — sample data", accent: "#6366f1" }) : null;
  const testResult = sp.test?.startsWith("ok:") ? { ok: true, msg: sp.test.slice(3) } : sp.test?.startsWith("fail:") ? { ok: false, msg: sp.test.slice(5) } : null;

  return (
    <main>
      <PageHeader
        title="📧 Email templates"
        sub="Every transactional email the platform sends. Edit the subject and body — {{variables}} are filled in automatically at send time."
      />
      {sp.saved === "1" && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ Template saved — all future emails use your version.</p>}
      {sp.saved === "reset" && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ Reset to the built-in default.</p>}
      {sp.error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{sp.error}</p>}
      {testResult && (
        <p className={`mb-4 rounded-xl px-4 py-2.5 text-sm font-medium ${testResult.ok ? "bg-emerald-500/10 text-emerald-600" : "bg-red-500/10 text-red-600"}`}>
          {testResult.ok ? "📨 " : "⚠️ "}{testResult.msg}
        </p>
      )}

      <div className="grid gap-6 lg:grid-cols-[320px_1fr]">
        {/* Template list */}
        <div className="space-y-2">
          {EMAIL_TEMPLATES.map((t) => {
            const o = overrideFor(t.key);
            return (
              <Link
                key={t.key}
                href={`/admin/templates?key=${t.key}`}
                className={`block rounded-2xl border p-3.5 backdrop-blur-xl transition ${
                  activeKey === t.key ? "border-indigo-400/70 bg-indigo-500/10 shadow-lg shadow-indigo-500/10" : "border-white/70 bg-white/60 hover:border-indigo-300/70"
                }`}
              >
                <div className="flex items-center justify-between gap-2">
                  <span className="text-sm font-bold text-zinc-100">{t.label}</span>
                  {o ? <Badge className="bg-violet-500/10 text-violet-600">Customized</Badge> : <Badge className="bg-zinc-500/10 text-zinc-500">Default</Badge>}
                </div>
                <p className="mt-1 text-[11px] leading-relaxed text-zinc-500">{t.description}</p>
                {o && <p className="mt-1 text-[10px] text-zinc-600">Edited {fmtDateTime(o.updatedAt)}</p>}
              </Link>
            );
          })}
        </div>

        {/* Editor + preview */}
        {!def ? (
          <Card className="flex h-fit items-center justify-center p-14 text-sm text-zinc-500">
            ← Pick a template to edit it and see a live preview.
          </Card>
        ) : (
          <div className="space-y-5">
            <Card className="p-5">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <div>
                  <h2 className="text-sm font-bold text-zinc-100">{def.label} <span className="font-mono text-xs font-normal text-zinc-500">({def.key})</span></h2>
                  <p className="text-xs text-zinc-500">{def.description}</p>
                </div>
                <form action={testEmailTemplate.bind(null, def.key)}>
                  <button className={btn.secondary}>📨 Send test to me</button>
                </form>
              </div>

              <div className="mt-3 rounded-xl bg-indigo-500/5 px-4 py-3">
                <div className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Available variables — click nothing, just type them into subject or body</div>
                <div className="mt-1.5 flex flex-wrap gap-1.5">
                  {["accent", ...Object.keys(def.variables)].map((v) => (
                    <code key={v} className="rounded-md bg-white/70 px-2 py-0.5 font-mono text-[11px] text-indigo-700">{`{{${v}}}`}</code>
                  ))}
                </div>
              </div>

              <form action={saveEmailTemplate.bind(null, def.key)} className="mt-4 space-y-4">
                <Field name="subject" title="Subject">
                  <input id="subject" name="subject" required defaultValue={override?.subject ?? def.subject} className={input} />
                </Field>
                <Field name="body" title="Body (HTML)">
                  <textarea id="body" name="body" required rows={14} defaultValue={override?.body ?? def.body} className={`${input} font-mono !text-xs leading-relaxed`} spellCheck={false} />
                </Field>
                <button className={btn.primary}>Save template</button>
              </form>
              {override && (
                <form action={resetEmailTemplate.bind(null, def.key)} className="mt-2">
                  <button className={btn.secondary}>↩ Reset to default</button>
                </form>
              )}
            </Card>

            <Card className="overflow-hidden p-0">
              <div className="flex items-center justify-between border-b border-zinc-800/50 px-5 py-3">
                <h3 className="text-sm font-bold text-zinc-100">Live preview <span className="text-xs font-normal text-zinc-500">(sample data{override ? ", your saved version" : ", default"})</span></h3>
                <span className="text-xs text-zinc-500">Subject: <b className="text-zinc-300">{preview?.subject}</b></span>
              </div>
              <iframe title="Email preview" srcDoc={preview?.html ?? ""} className="h-[520px] w-full bg-[#eef1fb]" sandbox="" />
            </Card>
          </div>
        )}
      </div>
    </main>
  );
}
