import Link from "next/link";
import { toFa } from "@/lib/format";

export default function Pagination({
  currentPage,
  totalPages,
  basePath,
}: {
  currentPage: number;
  totalPages: number;
  basePath: string;
}) {
  if (totalPages <= 1) return null;

  const pages = Array.from({ length: totalPages }, (_, i) => i + 1);

  function hrefFor(page: number) {
    return page === 1 ? basePath : `${basePath}?page=${page}`;
  }

  const prevDisabled = currentPage === 1;
  const nextDisabled = currentPage === totalPages;

  return (
    <nav
      aria-label="صفحه‌بندی"
      className="mt-12 flex flex-wrap items-center justify-center gap-2"
    >
      <Link
        href={hrefFor(Math.max(1, currentPage - 1))}
        aria-disabled={prevDisabled}
        tabIndex={prevDisabled ? -1 : undefined}
        className={`flex h-10 items-center justify-center rounded-full border px-4 text-sm font-medium transition-colors ${
          prevDisabled
            ? "pointer-events-none border-black/5 text-foreground/30"
            : "border-black/10 text-secondary hover:border-primary hover:text-primary"
        }`}
      >
        قبلی
      </Link>

      {pages.map((p) => (
        <Link
          key={p}
          href={hrefFor(p)}
          aria-current={p === currentPage ? "page" : undefined}
          className={`flex h-10 w-10 items-center justify-center rounded-full text-sm font-semibold transition-colors ${
            p === currentPage
              ? "bg-primary text-white"
              : "text-secondary hover:bg-primary/10"
          }`}
        >
          {toFa(p)}
        </Link>
      ))}

      <Link
        href={hrefFor(Math.min(totalPages, currentPage + 1))}
        aria-disabled={nextDisabled}
        tabIndex={nextDisabled ? -1 : undefined}
        className={`flex h-10 items-center justify-center rounded-full border px-4 text-sm font-medium transition-colors ${
          nextDisabled
            ? "pointer-events-none border-black/5 text-foreground/30"
            : "border-black/10 text-secondary hover:border-primary hover:text-primary"
        }`}
      >
        بعدی
      </Link>
    </nav>
  );
}
