"use client";

import { cn } from "@/lib/utils/cn";

interface PaginationProps {
  /** Zero-based current page (matches Spring's Pageable). */
  page: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  labels?: { prev: string; next: string };
}

/** Numeric pagination with prev/next, windowed around the current page. */
export function Pagination({ page, totalPages, onPageChange, labels }: PaginationProps) {
  if (totalPages <= 1) return null;

  const prev = labels?.prev ?? "← पिछला / Prev";
  const next = labels?.next ?? "अगला / Next →";

  const windowSize = 2;
  const pages: (number | "…")[] = [];
  for (let p = 0; p < totalPages; p++) {
    const nearEdge = p === 0 || p === totalPages - 1;
    const nearCurrent = Math.abs(p - page) <= windowSize;
    if (nearEdge || nearCurrent) {
      pages.push(p);
    } else if (pages[pages.length - 1] !== "…") {
      pages.push("…");
    }
  }

  const btn =
    "inline-flex h-9 min-w-9 items-center justify-center rounded-md border px-2 text-sm transition-colors";

  return (
    <nav aria-label="Pagination" className="flex flex-wrap items-center justify-center gap-1.5">
      <button
        onClick={() => onPageChange(page - 1)}
        disabled={page === 0}
        className={cn(btn, "border-gray-300 px-3 text-gray-700 hover:bg-gray-50 disabled:opacity-40")}
      >
        {prev}
      </button>
      {pages.map((p, i) =>
        p === "…" ? (
          <span key={`gap-${i}`} className="px-1 text-sm text-gray-400">…</span>
        ) : (
          <button
            key={p}
            onClick={() => onPageChange(p)}
            aria-current={p === page ? "page" : undefined}
            className={cn(
              btn,
              p === page
                ? "border-indigo-600 bg-indigo-600 font-semibold text-white"
                : "border-gray-300 text-gray-700 hover:bg-gray-50"
            )}
          >
            {p + 1}
          </button>
        )
      )}
      <button
        onClick={() => onPageChange(page + 1)}
        disabled={page >= totalPages - 1}
        className={cn(btn, "border-gray-300 px-3 text-gray-700 hover:bg-gray-50 disabled:opacity-40")}
      >
        {next}
      </button>
    </nav>
  );
}
