import Link from "next/link";

export function Pager({
  basePath,
  prevCursor,
  nextCursor,
  page = 1,
  extra = {},
}: {
  basePath: string;
  prevCursor?: string | null;
  nextCursor?: string | null;
  page?: number;
  extra?: Record<string, string | undefined>;
}) {
  const make = ({
    nextPage,
    nextPageCursor,
    back,
  }: {
    nextPage: number;
    nextPageCursor?: string;
    back?: boolean;
  }) => {
    const sp = new URLSearchParams();
    for (const [k, v] of Object.entries(extra)) if (v) sp.set(k, v);
    if (nextPageCursor) sp.set("cursor", nextPageCursor);
    if (back) sp.set("back", "1");
    if (nextPage > 1) sp.set("page", String(nextPage));
    const qs = sp.toString();
    return qs ? `${basePath}?${qs}` : basePath;
  };

  const previousHref =
    page > 1 && prevCursor
      ? make({ nextPage: page - 1, nextPageCursor: prevCursor, back: true })
      : null;
  const nextHref = nextCursor
    ? make({ nextPage: page + 1, nextPageCursor: nextCursor })
    : null;

  return (
    <div className="mt-4 flex justify-between text-sm">
      {previousHref ? (
        <Link href={previousHref} className="text-blue-300 hover:text-blue-200">
          ← prev
        </Link>
      ) : (
        <span className="text-neutral-600">← prev</span>
      )}
      <span className="text-neutral-500">page {page}</span>
      {nextHref ? (
        <Link href={nextHref} className="text-blue-300 hover:text-blue-200">
          next →
        </Link>
      ) : (
        <span className="text-neutral-600">end</span>
      )}
    </div>
  );
}
