import Link from "next/link";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { bulkTexts } from "@/lib/i18n/bulk";

function buildHref(
  basePath: string,
  params: Record<string, string | undefined>,
  page: number,
): string {
  const search = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if (value) search.set(key, value);
  }
  if (page > 1) search.set("page", String(page));
  const qs = search.toString();
  return qs ? `${basePath}?${qs}` : basePath;
}

/** Server-side pagination footer — plain links, no client JS. */
export function Pager({
  basePath,
  params = {},
  page,
  perPage,
  total,
}: {
  basePath: string;
  params?: Record<string, string | undefined>;
  page: number;
  perPage: number;
  total: number;
}) {
  if (total <= perPage) return null;
  const pages = Math.max(1, Math.ceil(total / perPage));
  const from = total === 0 ? 0 : (page - 1) * perPage + 1;
  const to = Math.min(total, page * perPage);

  const linkClass =
    "inline-flex h-8 items-center gap-1 rounded-lg border px-2.5 text-sm font-medium transition-colors hover:bg-muted";
  const disabledClass = "pointer-events-none opacity-40";

  return (
    <div className="flex flex-col items-center justify-between gap-3 border-t px-4 py-3 sm:flex-row">
      <p className="font-mono text-xs text-muted-foreground tabular-nums">
        {bulkTexts.paginationSummary(from, to, total)}
      </p>
      <div className="flex items-center gap-2">
        <Link
          href={buildHref(basePath, params, Math.max(1, page - 1))}
          className={cn(linkClass, page <= 1 && disabledClass)}
          aria-disabled={page <= 1}
        >
          <ChevronLeft className="size-3.5" />
          {bulkTexts.previous}
        </Link>
        <Link
          href={buildHref(basePath, params, Math.min(pages, page + 1))}
          className={cn(linkClass, page >= pages && disabledClass)}
          aria-disabled={page >= pages}
        >
          {bulkTexts.next}
          <ChevronRight className="size-3.5" />
        </Link>
      </div>
    </div>
  );
}

export default Pager;
