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

export function Pagination({
  page,
  totalPages,
  basePath,
  params,
  labels,
}: {
  page: number;
  totalPages: number;
  basePath: string;
  params: Record<string, string | undefined>;
  labels: { previous: string; next: string };
}) {
  if (totalPages <= 1) return null;

  const href = (target: number) => {
    const query = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value && key !== "page") query.set(key, value);
    });
    if (target > 1) query.set("page", String(target));
    const qs = query.toString();
    return `${basePath}${qs ? `?${qs}` : ""}`;
  };

  const pages = Array.from({ length: totalPages }, (_, index) => index + 1).filter(
    (value) => value === 1 || value === totalPages || Math.abs(value - page) <= 1,
  );

  return (
    <nav className="mt-14 flex items-center justify-center gap-1.5 border-t border-line pt-8" aria-label="Pagination">
      <Link
        href={href(Math.max(1, page - 1))}
        aria-disabled={page === 1}
        className={cn(
          "flex h-10 w-10 items-center justify-center border border-line bg-cream text-walnut transition-colors hover:border-line-strong hover:text-charcoal",
          page === 1 && "pointer-events-none opacity-45",
        )}
        aria-label={labels.previous}
      >
        <ChevronLeft className="h-4 w-4 rtl:rotate-180" />
      </Link>
      {pages.map((value, index) => (
        <span key={value} className="flex items-center">
          {index > 0 && value - pages[index - 1] > 1 && <span className="px-1 text-pebble">…</span>}
          <Link
            href={href(value)}
            aria-current={value === page ? "page" : undefined}
            className={cn(
              "flex h-10 min-w-10 items-center justify-center border px-2.5 text-[14px] transition-colors",
              value === page ? "border-charcoal bg-charcoal text-ivory" : "border-line bg-cream text-walnut hover:border-line-strong hover:text-charcoal",
            )}
          >
            {value}
          </Link>
        </span>
      ))}
      <Link
        href={href(Math.min(totalPages, page + 1))}
        aria-disabled={page === totalPages}
        className={cn(
          "flex h-10 w-10 items-center justify-center border border-line bg-cream text-walnut transition-colors hover:border-line-strong hover:text-charcoal",
          page === totalPages && "pointer-events-none opacity-45",
        )}
        aria-label={labels.next}
      >
        <ChevronRight className="h-4 w-4 rtl:rotate-180" />
      </Link>
    </nav>
  );
}
