import type { Metadata } from "next";
import Link from "next/link";
import {
  requireAdmin,
  setGameStatusAction,
  toggleGameFlagAction,
} from "@/lib/admin-actions";
import { listAllGamesAdmin } from "@/lib/games";
import { DeleteGameButton } from "@/components/admin/DeleteGameButton";
import { Pagination, withQuery } from "@/components/game/Pagination";

export const metadata: Metadata = {
  title: "Manage Games",
  description: "Admin game management.",
};

const STATUS_STYLES: Record<string, string> = {
  published: "bg-emerald-500/15 text-emerald-300 border-emerald-500/40",
  draft: "bg-slate-500/15 text-slate-300 border-slate-500/40",
  disabled: "bg-red-500/15 text-red-300 border-red-500/40",
};

interface ManageGamesPageProps {
  searchParams: Promise<{ status?: string; q?: string; page?: string }>;
}

/** Game management: status filter, search, publish controls, flags, delete. */
export default async function ManageGamesPage({ searchParams }: ManageGamesPageProps) {
  await requireAdmin();
  const params = await searchParams;
  const status = ["published", "draft", "disabled"].includes(params.status ?? "")
    ? params.status!
    : "";
  const q = params.q?.trim() ?? "";
  const page = Math.max(1, Number.parseInt(params.page ?? "1", 10) || 1);

  const result = await listAllGamesAdmin({
    status: status || undefined,
    q: q || undefined,
    page,
  });

  const hrefFor = (overrides: Record<string, string | undefined>) =>
    withQuery("/admin/games", {
      status: status || undefined,
      q: q || undefined,
      ...overrides,
    });

  return (
    <div>
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white sm:text-3xl">Games</h1>
          <p className="mt-1 text-sm text-slate-400">
            {result.total} {result.total === 1 ? "game" : "games"} in the catalog.
          </p>
        </div>
        <Link
          href="/admin/games/new"
          className="inline-flex h-10 items-center rounded-xl bg-brand-600 px-4 text-sm font-semibold text-white hover:bg-brand-500"
        >
          + Add game
        </Link>
      </div>

      <div className="mt-6 flex flex-wrap gap-2">
        {["", "published", "draft", "disabled"].map((s) => (
          <Link
            key={s || "all"}
            href={hrefFor({ status: s || undefined, page: undefined })}
            aria-current={(status || "") === s ? "page" : undefined}
            className={`rounded-full border px-4 py-1.5 text-sm font-medium capitalize ${
              (status || "") === s
                ? "border-brand-500 bg-brand-600/20 text-white"
                : "border-slate-700 text-slate-300 hover:border-slate-500"
            }`}
          >
            {s || "All"}
          </Link>
        ))}
        <form action="/admin/games" method="get" className="ml-auto flex gap-2" role="search">
          {status ? <input type="hidden" name="status" value={status} /> : null}
          <label htmlFor="admin-q" className="sr-only">Search games</label>
          <input
            id="admin-q"
            name="q"
            type="search"
            defaultValue={q}
            placeholder="Search title, slug…"
            className="h-9 rounded-xl border border-slate-700 bg-slate-900 px-3 text-sm text-white placeholder:text-slate-500"
          />
          <button type="submit" className="h-9 rounded-xl bg-slate-800 px-3 text-sm font-semibold text-white hover:bg-slate-700">
            Search
          </button>
        </form>
      </div>

      <div className="mt-4 overflow-x-auto rounded-2xl border border-slate-800">
        <table className="w-full min-w-[760px] text-left text-sm">
          <thead>
            <tr className="border-b border-slate-800 text-xs tracking-wider text-slate-500 uppercase">
              <th scope="col" className="px-4 py-3">Game</th>
              <th scope="col" className="px-4 py-3">Status</th>
              <th scope="col" className="px-4 py-3">Flags</th>
              <th scope="col" className="px-4 py-3">Publish</th>
              <th scope="col" className="px-4 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-800">
            {result.games.map((g) => (
              <tr key={g.numericId} className="bg-slate-900/40">
                <td className="px-4 py-3">
                  <p className="font-medium text-white">{g.title}</p>
                  <p className="text-xs text-slate-500">
                    /{g.slug} · {g.categoryName}
                  </p>
                </td>
                <td className="px-4 py-3">
                  <span className={`inline-block rounded-full border px-2.5 py-0.5 text-xs font-semibold capitalize ${STATUS_STYLES[g.status] ?? ""}`}>
                    {g.status}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <div className="flex gap-2">
                    <form action={toggleGameFlagAction.bind(null, g.numericId, "featured", !g.featured)}>
                      <button
                        type="submit"
                        title={g.featured ? "Remove featured" : "Mark featured"}
                        aria-pressed={g.featured}
                        aria-label={`${g.featured ? "Remove featured from" : "Mark featured:"} ${g.title}`}
                        className={`rounded-lg border px-2 py-1 text-xs font-semibold ${g.featured ? "border-brand-500/60 bg-brand-600/20 text-brand-200" : "border-slate-700 text-slate-500 hover:text-slate-300"}`}
                      >
                        ★
                      </button>
                    </form>
                    <form action={toggleGameFlagAction.bind(null, g.numericId, "trending", !g.trending)}>
                      <button
                        type="submit"
                        title={g.trending ? "Remove trending" : "Mark trending"}
                        aria-pressed={g.trending}
                        aria-label={`${g.trending ? "Remove trending from" : "Mark trending:"} ${g.title}`}
                        className={`rounded-lg border px-2 py-1 text-xs font-semibold ${g.trending ? "border-brand-500/60 bg-brand-600/20 text-brand-200" : "border-slate-700 text-slate-500 hover:text-slate-300"}`}
                      >
                        ▲
                      </button>
                    </form>
                  </div>
                </td>
                <td className="px-4 py-3">
                  <div className="flex gap-2">
                    {g.status !== "published" ? (
                      <form action={setGameStatusAction.bind(null, g.numericId, "published")}>
                        <button type="submit" className="rounded-lg border border-emerald-500/40 bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold text-emerald-300 hover:bg-emerald-500/20">
                          Publish
                        </button>
                      </form>
                    ) : (
                      <form action={setGameStatusAction.bind(null, g.numericId, "draft")}>
                        <button type="submit" className="rounded-lg border border-slate-600 px-2.5 py-1 text-xs font-semibold text-slate-300 hover:border-slate-400">
                          Unpublish
                        </button>
                      </form>
                    )}
                    {g.status !== "disabled" ? (
                      <form action={setGameStatusAction.bind(null, g.numericId, "disabled")}>
                        <button type="submit" className="rounded-lg border border-slate-700 px-2.5 py-1 text-xs font-semibold text-slate-400 hover:text-red-300">
                          Disable
                        </button>
                      </form>
                    ) : null}
                  </div>
                </td>
                <td className="px-4 py-3">
                  <div className="flex justify-end gap-2">
                    <Link
                      href={`/admin/games/${g.numericId}/edit`}
                      className="rounded-lg border border-slate-700 px-3 py-1.5 text-xs font-semibold text-slate-200 hover:border-slate-500"
                    >
                      Edit
                    </Link>
                    <DeleteGameButton id={g.numericId} title={g.title} />
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {result.games.length === 0 ? (
          <p className="px-4 py-8 text-center text-sm text-slate-400">
            No games match. Adjust the filter or add a new game.
          </p>
        ) : null}
      </div>

      <Pagination
        page={result.page}
        totalPages={result.totalPages}
        buildHref={(p) => hrefFor({ page: p > 1 ? String(p) : undefined })}
      />
    </div>
  );
}
