"use client";
import { useEffect, useState } from "react";

const TEMPLATE_LABELS: Record<string, { title: string; desc: string; vars: string[] }> = {
  welcome: { title: "Welcome Email", desc: "Sent immediately when someone registers.", vars: ["siteName", "name", "appUrl"] },
  verify: { title: "Verify Email", desc: "Sent on registration with a link to confirm the email address.", vars: ["siteName", "name", "verifyUrl", "appUrl"] },
  receipt: { title: "Tip / Support Receipt", desc: "Sent after a confirmed tip or one-time support payment.", vars: ["siteName", "description", "amount", "date", "appUrl"] },
  invoice: { title: "Invoice (Subscriptions)", desc: "Sent after a confirmed membership subscription payment.", vars: ["siteName", "name", "description", "amount", "date", "invoiceNumber", "appUrl"] },
  shop_purchase: { title: "Shop Purchase", desc: "Sent after a confirmed shop or pay-per-view video purchase.", vars: ["siteName", "name", "description", "amount", "appUrl"] },
  mission_announcement: { title: "New Mission Announcement", desc: "Sent to all members when an admin creates a new mission/target.", vars: ["siteName", "missionTitle", "missionDescription", "missionGoal", "pointsLine", "appUrl"] },
  video_alert: { title: "New Video Alert", desc: "Sent to members who've opted in, when an admin publishes a new video.", vars: ["siteName", "videoTitle", "videoDescription", "videoUrl", "appUrl"] },
  ebook_claim: { title: "Free Ebook Claim", desc: "Sent when someone subscribes to a paid plan, offering the configured free ebook.", vars: ["siteName", "name", "ebookTitle", "claimUrl", "appUrl"] },
};

export default function AdminEmailsPage() {
  const [templates, setTemplates] = useState<Record<string, { subject: string; body: string }>>({});
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/emails")
      .then((r) => r.json())
      .then((d) => {
        setTemplates(d.templates);
        setLoading(false);
      });
  }, []);

  function update(key: string, field: "subject" | "body", value: string) {
    setTemplates((t) => ({ ...t, [key]: { ...t[key], [field]: value } }));
  }

  async function save() {
    setSaving(true);
    setSaved(false);
    await fetch("/api/admin/emails", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ templates }),
    });
    setSaving(false);
    setSaved(true);
  }

  const inputCls = "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600";

  if (loading) return <p className="text-neutral-500">Loading...</p>;

  return (
    <div className="max-w-2xl">
      <h2 className="text-lg font-semibold mb-1">Email Templates</h2>
      <p className="text-xs text-neutral-500 mb-6">
        All emails are sent via SMTP (configured in Admin &gt; Email Campaign). HTML is supported.
      </p>

      {Object.entries(TEMPLATE_LABELS).map(([key, meta]) => (
        <div key={key} className="card p-5 space-y-3 mb-6">
          <div>
            <h3 className="font-semibold text-sm">{meta.title}</h3>
            <p className="text-xs text-neutral-500">{meta.desc}</p>
            <p className="text-xs text-neutral-600 mt-1">
              Placeholders: {meta.vars.map((v) => <code key={v} className="mr-1">{"{{" + v + "}}"}</code>)}
            </p>
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Subject</label>
            <input
              value={templates[key]?.subject || ""}
              onChange={(e) => update(key, "subject", e.target.value)}
              className={inputCls}
            />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Body (HTML)</label>
            <textarea
              value={templates[key]?.body || ""}
              onChange={(e) => update(key, "body", e.target.value)}
              rows={6}
              className={inputCls}
            />
          </div>
        </div>
      ))}

      <div className="flex items-center gap-3">
        <button onClick={save} disabled={saving} className="btn-primary px-5 py-2 text-sm">
          {saving ? "Saving..." : "Save All Templates"}
        </button>
        {saved && <span className="text-green-500 text-sm">✓ Saved</span>}
      </div>
    </div>
  );
}
