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

const PAGE_DEFS = [
  { slug: "about", label: "About" },
  { slug: "contact", label: "Contact" },
  { slug: "terms", label: "Terms and Conditions" },
  { slug: "privacy", label: "Privacy Policy" },
  { slug: "refund", label: "Refund Policy" },
];

export default function StaticPagesEditor() {
  const [pages, setPages] = useState<Record<string, { title: string; content: string }>>({});
  const [openSlug, setOpenSlug] = useState<string | null>(null);
  const [saving, setSaving] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/static-pages")
      .then((r) => r.json())
      .then((rows: { slug: string; title: string; content: string }[]) => {
        const map: Record<string, { title: string; content: string }> = {};
        for (const r of rows) map[r.slug] = { title: r.title, content: r.content };
        setPages(map);
      });
  }, []);

  function update(slug: string, key: "title" | "content", value: string) {
    setPages((prev) => ({ ...prev, [slug]: { ...(prev[slug] || { title: "", content: "" }), [key]: value } }));
  }

  async function save(slug: string) {
    setSaving(slug);
    const page = pages[slug] || { title: "", content: "" };
    await fetch(`/api/admin/static-pages/${slug}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(page),
    });
    setSaving(null);
  }

  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";

  return (
    <div className="space-y-3">
      {PAGE_DEFS.map((def) => (
        <div key={def.slug} className="card overflow-hidden">
          <button
            onClick={() => setOpenSlug(openSlug === def.slug ? null : def.slug)}
            className="w-full flex items-center justify-between p-4 text-left"
          >
            <span className="font-semibold text-sm">{def.label}</span>
            <span className="text-neutral-500 text-xs">{openSlug === def.slug ? "Hide" : "Edit"}</span>
          </button>
          {openSlug === def.slug && (
            <div className="p-4 border-t border-neutral-800">
              <label className="block text-xs text-neutral-500 mb-1.5">Page title</label>
              <input
                value={pages[def.slug]?.title ?? ""}
                onChange={(e) => update(def.slug, "title", e.target.value)}
                placeholder={def.label}
                className={`${inputCls} mb-3`}
              />
              <label className="block text-xs text-neutral-500 mb-1.5">
                Content (HTML) — use <code>{"<h2>"}</code> and <code>{"<p>"}</code> tags. <code>{"{{siteName}}"}</code> and{" "}
                <code>{"{{llcName}}"}</code> get replaced automatically.
              </label>
              <textarea
                value={pages[def.slug]?.content ?? ""}
                onChange={(e) => update(def.slug, "content", e.target.value)}
                rows={10}
                placeholder="Leave blank to use the built-in default text"
                className={`${inputCls} font-mono text-xs`}
              />
              <button onClick={() => save(def.slug)} disabled={saving === def.slug} className="btn-primary px-4 py-2 text-sm mt-3">
                {saving === def.slug ? "Saving..." : "Save Page"}
              </button>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
