import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { isAdmin } from "@/lib/admin-auth";
import { TIERS, formatUSD } from "@/lib/tiers";
import { approveDonation, rejectDonation, editDonation } from "./actions";

export const dynamic = "force-dynamic";
export const metadata = { title: "Moderate — PIFF Admin" };

export default async function ModeratePage() {
  if (!isAdmin()) redirect("/admin/login");

  const donations = await prisma.donation.findMany({
    orderBy: { createdAt: "desc" },
    take: 200,
  });

  return (
    <section className="mx-auto max-w-4xl px-6 py-12">
      <h1 className="font-display text-3xl font-bold text-text">
        Donation moderation queue
      </h1>
      <p className="mt-2 text-textmuted">
        Approve, reject, or edit donor messages. Approved donations render on
        the public house and are added to the wall of donors.
      </p>

      <div className="mt-8 space-y-6">
        {donations.length === 0 && (
          <div className="rounded-lg border border-border bg-surface p-6 text-textmuted">
            No donations yet.
          </div>
        )}

        {donations.map((d) => {
          const tier = TIERS[d.tierId as keyof typeof TIERS];
          return (
            <div
              key={d.id}
              className="rounded-2xl border border-border bg-white p-5"
            >
              <div className="flex items-baseline justify-between">
                <div>
                  <div className="text-xs uppercase tracking-wider text-textmuted">
                    {tier?.label ?? d.tierId} · {d.regionId}
                  </div>
                  <div className="font-display text-xl font-bold text-text">
                    {formatUSD(d.amountCents)} —{" "}
                    <span
                      className={
                        d.status === "APPROVED"
                          ? "text-primary"
                          : d.status === "REJECTED"
                            ? "text-red-700"
                            : "text-textmuted"
                      }
                    >
                      {d.status}
                    </span>
                  </div>
                </div>
                <div className="text-right text-xs text-textmuted">
                  {new Date(d.createdAt).toLocaleString()}
                </div>
              </div>

              <div className="mt-3 grid gap-2 text-sm">
                <div>
                  <span className="font-medium">From:</span>{" "}
                  {d.donorName ?? "(no name)"}
                  {d.isAnonymous && (
                    <span className="ml-2 rounded bg-surface px-2 py-0.5 text-xs text-textmuted">
                      anonymous (hidden publicly)
                    </span>
                  )}
                </div>
                <div>
                  <span className="font-medium">Email:</span> {d.donorEmail}
                </div>
                <div>
                  <span className="font-medium">Message:</span>{" "}
                  <span className="italic">{d.message}</span>
                </div>
                {d.websiteUrl && (
                  <div className="break-all">
                    <span className="font-medium">URL:</span> {d.websiteUrl}
                  </div>
                )}
                {d.notes && (
                  <div className="text-xs text-textmuted">
                    <span className="font-medium">Notes:</span> {d.notes}
                  </div>
                )}
              </div>

              <details className="mt-3">
                <summary className="cursor-pointer text-sm text-primary">
                  Edit displayed text
                </summary>
                <form action={editDonation} className="mt-3 space-y-2">
                  <input type="hidden" name="id" value={d.id} />
                  <input
                    type="text"
                    name="message"
                    defaultValue={d.message}
                    maxLength={60}
                    className="w-full rounded-lg border border-border p-2 text-sm"
                  />
                  <input
                    type="text"
                    name="donorName"
                    defaultValue={d.donorName ?? ""}
                    placeholder="Display name"
                    className="w-full rounded-lg border border-border p-2 text-sm"
                  />
                  <input
                    type="url"
                    name="websiteUrl"
                    defaultValue={d.websiteUrl ?? ""}
                    placeholder="https://..."
                    className="w-full rounded-lg border border-border p-2 text-sm"
                  />
                  <button
                    type="submit"
                    className="rounded-full border border-border px-4 py-1.5 text-sm hover:bg-surface"
                  >
                    Save edits
                  </button>
                </form>
              </details>

              <div className="mt-4 flex gap-2">
                {d.status !== "APPROVED" && (
                  <form action={approveDonation}>
                    <input type="hidden" name="id" value={d.id} />
                    <button
                      type="submit"
                      className="rounded-full bg-primary px-4 py-1.5 text-sm font-medium text-white hover:bg-primaryDark"
                    >
                      Approve
                    </button>
                  </form>
                )}
                {d.status !== "REJECTED" && (
                  <form action={rejectDonation}>
                    <input type="hidden" name="id" value={d.id} />
                    <button
                      type="submit"
                      className="rounded-full border border-border px-4 py-1.5 text-sm hover:bg-surface"
                    >
                      Reject
                    </button>
                  </form>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}
