import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { updateStaticPage } from "@/lib/actions/pages";

const PAGE_LABELS: Record<string, string> = {
  "/about": "About Us",
  "/privacy-policy": "Privacy Policy",
  "/terms": "Terms & Conditions",
  "/shipping-policy": "Shipping Policy",
  "/return-refund-policy": "Return & Refund Policy",
};
const ORDER = Object.keys(PAGE_LABELS);

export default async function AdminWebsitePage({
  searchParams,
}: {
  searchParams: Promise<{ edit?: string; error?: string }>;
}) {
  const { edit, error } = await searchParams;
  const pages = await prisma.staticPage.findMany();
  const sorted = ORDER.map((path) => pages.find((p) => p.path === path)).filter((p) => p != null);
  const editing = edit ? sorted.find((p) => p.path === edit) : null;

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Website / Pages</h1>
      <p className="mt-1 max-w-2xl text-sm text-stone-500">
        Edit these static pages without touching code. Two things live elsewhere on purpose: the homepage banner and
        sections are under <Link href="/iv-manage-84x2/marketing" className="text-rose-700 hover:underline">Marketing</Link>{" "}
        (already database-driven), and FAQ isn&apos;t editable here yet — each answer has its own inline links, which
        this simple editor would flatten into plain text, so it&apos;s still in code for now.
      </p>

      {error && <p className="mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      {editing ? (
        <form action={updateStaticPage.bind(null, editing.path)} className="mt-6 max-w-2xl space-y-3 rounded-lg border border-rose-100 bg-white p-4">
          <div>
            <label className="text-xs text-stone-500">Page title</label>
            <input name="title" defaultValue={editing.title} required className="mt-1 block w-full rounded-md border border-stone-300 px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="text-xs text-stone-500">
              Body — blank line = new paragraph, a line starting <code className="rounded bg-stone-100 px-1">## </code> is a
              subheading, lines starting <code className="rounded bg-stone-100 px-1">- </code> become a bullet list
            </label>
            <textarea name="body" defaultValue={editing.body} required rows={16} className="mt-1 block w-full rounded-md border border-stone-300 px-3 py-2 font-mono text-xs" />
          </div>
          <div className="flex gap-2">
            <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
              Save
            </button>
            <Link href="/iv-manage-84x2/website" className="rounded-md border border-stone-300 px-4 py-2 text-sm font-medium text-stone-600 hover:bg-stone-50">
              Cancel
            </Link>
          </div>
        </form>
      ) : (
        <div className="mt-6 overflow-hidden rounded-lg border border-rose-100 bg-white">
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Page</th>
                <th className="p-3">Title</th>
                <th className="p-3">Last updated</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {sorted.map((p) => (
                <tr key={p.path}>
                  <td className="p-3 font-medium text-stone-800">{PAGE_LABELS[p.path]}</td>
                  <td className="p-3 text-stone-600">{p.title}</td>
                  <td className="p-3 text-stone-500">{formatDate(p.updatedAt)}</td>
                  <td className="p-3 text-right">
                    <Link href={`/iv-manage-84x2/website?edit=${encodeURIComponent(p.path)}`} className="text-xs font-medium text-rose-700 hover:underline">
                      Edit
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
