import type { Metadata } from "next";
import Link from "next/link";
import { GameCard, GameGrid } from "@/components/game/GameCard";
import { Pagination, withQuery } from "@/components/game/Pagination";
import { SearchBar } from "@/components/ui/SearchBar";
import { EmptyState } from "@/components/ui/Section";
import { listGames, parseSort } from "@/lib/games";
import { CATEGORIES, categoryBySlug } from "@/lib/site";

export const metadata: Metadata = {
  title: "All Games",
  description:
    "Browse the full curated catalog of browser games. Filter by category, search and sort.",
  alternates: { canonical: "/games" },
};

interface GamesPageProps {
  searchParams: Promise<{ q?: string; category?: string; sort?: string; page?: string }>;
}

const SORT_OPTIONS = [
  { value: "newest", label: "Newest first" },
  { value: "az", label: "Alphabetical (A–Z)" },
] as const;

/**
 * All-games listing: search (name, description, category, developer),
 * category filter, sorting (newest / A–Z — no invented popularity data),
 * page-based pagination.
 */
export default async function GamesPage({ searchParams }: GamesPageProps) {
  const params = await searchParams;
  const query = params.q?.trim() ?? "";
  const categoryParam = params.category?.trim().toLowerCase() ?? "";
  const activeCategory = categoryParam
    ? (categoryBySlug(categoryParam)?.slug ?? "")
    : "";
  const sort = parseSort(params.sort);
  const page = Math.max(1, Number.parseInt(params.page ?? "1", 10) || 1);

  const result = await listGames({
    q: query,
    categorySlug: activeCategory || undefined,
    sort,
    page,
  });

  const hrefFor = (overrides: Record<string, string | undefined>) =>
    withQuery("/games", {
      q: query || undefined,
      category: activeCategory || undefined,
      sort,
      ...overrides,
    });

  return (
    <div className="shell py-10">
      <h1 className="text-3xl font-bold tracking-tight text-white sm:text-4xl">
        All Games
      </h1>
      <p className="mt-2 max-w-2xl text-slate-400">
        Search the curated catalog and filter by category.
        {result.total > 0 ? (
          <>
            {" "}
            Showing{" "}
            <span className="font-semibold text-slate-200">
              {result.games.length} of {result.total}
            </span>{" "}
            {result.total === 1 ? "game" : "games"}.
          </>
        ) : null}
      </p>

      <div className="mt-6 flex max-w-xl flex-col gap-4">
        <SearchBar id="games-search" defaultValue={query} />
        <form
          action="/games"
          method="get"
          className="flex flex-wrap items-center gap-2"
        >
          {query ? <input type="hidden" name="q" value={query} /> : null}
          {activeCategory ? (
            <input type="hidden" name="category" value={activeCategory} />
          ) : null}
          <label htmlFor="sort" className="text-sm text-slate-400">
            Sort by
          </label>
          <select
            id="sort"
            name="sort"
            defaultValue={sort}
            className="h-10 rounded-xl border border-slate-700 bg-slate-900 px-3 text-sm text-slate-100"
          >
            {SORT_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
          <button
            type="submit"
            className="inline-flex h-10 items-center rounded-xl bg-slate-800 px-4 text-sm font-semibold text-white hover:bg-slate-700"
          >
            Apply
          </button>
        </form>
      </div>

      <div className="mt-5">
        <ul className="flex flex-wrap gap-2" aria-label="Filter by category">
          <li>
            <Link
              href={hrefFor({ category: undefined, page: undefined })}
              aria-current={!activeCategory ? "page" : undefined}
              className={`inline-flex h-9 items-center rounded-full border px-4 text-sm font-medium transition-colors ${
                !activeCategory
                  ? "border-brand-500 bg-brand-600/20 text-white"
                  : "border-slate-700 bg-slate-900 text-slate-300 hover:border-slate-500 hover:text-white"
              }`}
            >
              All
            </Link>
          </li>
          {CATEGORIES.map((c) => (
            <li key={c.slug}>
              <Link
                href={hrefFor({ category: c.slug, page: undefined })}
                aria-current={activeCategory === c.slug ? "page" : undefined}
                className={`inline-flex h-9 items-center rounded-full border px-4 text-sm font-medium transition-colors ${
                  activeCategory === c.slug
                    ? "border-brand-500 bg-brand-600/20 text-white"
                    : "border-slate-700 bg-slate-900 text-slate-300 hover:border-slate-500 hover:text-white"
                }`}
              >
                {c.name}
              </Link>
            </li>
          ))}
        </ul>
      </div>

      <div className="mt-8" aria-live="polite">
        {result.games.length > 0 ? (
          <GameGrid>
            {result.games.map((game) => (
              <GameCard key={game.slug} game={game} />
            ))}
          </GameGrid>
        ) : (
          <EmptyState
            title={query ? `No games match “${query}”` : "No games found"}
            message={
              query || activeCategory
                ? "Try a different search term, or clear the filters to browse the full catalog."
                : "The catalog is empty right now. Check back soon."
            }
            actionHref="/games"
            actionLabel="Clear search & filters"
          />
        )}
      </div>

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