import type { Metadata } from "next";
import Link from "next/link";
import { ArrowLeft, Info } from "lucide-react";
import { notFound } from "next/navigation";
import { requireAdmin } from "@/lib/auth/admin-guard";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  formatAdminDateTime,
} from "@/components/admin";
import { Button } from "@/components/Button";
import { loadTemplate, defaultsFor } from "@/lib/email/templates-db";
import {
  saveTemplate,
  resetTemplateToDefault,
  sendTestEmail,
} from "../actions";

export const metadata: Metadata = { title: "Edit email template" };
export const dynamic = "force-dynamic";

export default async function EditEmailTemplatePage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  await requireAdmin();
  const { slug } = await params;
  const def = defaultsFor(slug);
  if (!def) notFound();
  const tpl = await loadTemplate(slug);
  const isCustomised = tpl.updatedAt.getTime() > 0;

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/email-templates"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          Back to templates
        </Link>
      </div>

      <AdminHeading
        eyebrow="Email template"
        title={tpl.name}
        lede={def.description ?? ""}
      />

      <form action={saveTemplate} className="flex flex-col gap-6">
        <input type="hidden" name="slug" value={slug} />
        <FormSection
          title="Copy"
          description="Use {{variable}} placeholders. Variables are listed below."
        >
          <div className="grid gap-4">
            <InputField
              label="Display name"
              name="name"
              required
              maxLength={200}
              defaultValue={tpl.name}
            />
            <InputField
              label="Description (internal)"
              name="description"
              maxLength={500}
              defaultValue={tpl.description}
            />
            <InputField
              label="Subject"
              name="subject"
              required
              maxLength={300}
              defaultValue={tpl.subject}
              hint="Shown in the recipient's inbox."
            />
            <TextareaField
              label="Body (plain text)"
              name="body"
              rows={16}
              maxLength={20_000}
              defaultValue={tpl.body}
              hint="Plain text only. HTML is not supported."
              className="font-mono !text-[13px] !leading-6"
            />
          </div>
        </FormSection>

        <FormSection title="Supported variables">
          <div className="flex flex-wrap gap-1.5">
            {tpl.variables.length === 0 ? (
              <span className="text-[13px] text-[var(--color-slate)]">
                No variables.
              </span>
            ) : (
              tpl.variables.map((v) => (
                <code
                  key={v}
                  className="rounded bg-[var(--color-mist)] px-2 py-0.5 text-[12px] font-mono text-[var(--color-blue)]"
                >
                  {"{{"}
                  {v}
                  {"}}"}
                </code>
              ))
            )}
          </div>
          <div className="mt-3 flex items-start gap-2 rounded-md border border-blue-200 bg-blue-50 p-3 text-[12px] text-blue-900">
            <Info className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
            <span>
              Unknown variables are replaced with empty strings — the recipient
              will never see literal <code>{"{{x}}"}</code> text.
            </span>
          </div>
        </FormSection>

        <div className="sticky bottom-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-[var(--color-line)] bg-white p-4 shadow-[0_16px_40px_rgba(10,15,46,0.06)]">
          <div className="text-[12px] text-[var(--color-slate)]">
            {isCustomised
              ? `Last edited ${formatAdminDateTime(tpl.updatedAt)}`
              : "Using built-in default — save to customise."}
          </div>
          <Button type="submit" variant="primary" className="!px-5 !py-2 !text-[13px]">
            Save template
          </Button>
        </div>
      </form>

      <div className="mt-8 grid gap-4 md:grid-cols-2">
        <FormSection
          title="Send a test email"
          description="Renders the template with sample values and sends it to any address."
        >
          <form action={sendTestEmail} className="flex flex-col gap-3">
            <input type="hidden" name="slug" value={slug} />
            <InputField
              label="Recipient"
              name="recipient"
              type="email"
              required
              placeholder="you@orthoglobe.org"
            />
            <Button type="submit" variant="secondary" className="!px-4 !py-2 !text-[13px]">
              Send test
            </Button>
          </form>
        </FormSection>

        {isCustomised && (
          <FormSection
            title="Reset to default"
            description="Clears any customisation and restores the built-in copy."
            tone="danger"
          >
            <form action={resetTemplateToDefault}>
              <input type="hidden" name="slug" value={slug} />
              <button
                type="submit"
                className="inline-flex items-center justify-center rounded-lg border border-red-300 bg-white px-4 py-2 text-[13px] font-semibold text-red-700 transition-colors hover:bg-red-50"
              >
                Reset to default
              </button>
            </form>
          </FormSection>
        )}
      </div>
    </>
  );
}
