import Link from 'next/link';
import { ChevronLeftIcon, ChevronRightIcon } from './Icons';

/** Page numbers to show: first, last, and a window around the current page, with gaps as null */
function windowed(page: number, count: number): (number | null)[] {
  const set = new Set([1, count, page - 1, page, page + 1].filter((p) => p >= 1 && p <= count));
  const sorted = [...set].sort((a, b) => a - b);
  const out: (number | null)[] = [];
  sorted.forEach((p, i) => {
    if (i > 0 && p - sorted[i - 1] > 1) out.push(null);
    out.push(p);
  });
  return out;
}

export function Pagination({ page, pageCount, href }: { page: number; pageCount: number; href: (p: number) => string }) {
  if (pageCount <= 1) return null;
  const current = Math.min(Math.max(1, page), pageCount);
  const cell = 'num inline-flex h-10 min-w-10 items-center justify-center rounded-lg px-3 text-sm font-semibold transition-colors';
  return (
    <nav aria-label="Pagination" className="mt-8 flex flex-wrap items-center justify-between gap-3 border-t border-rule pt-6">
      {current > 1 ? (
        <Link href={href(current - 1)} rel="prev" className="btn btn-quiet btn-sm">
          <ChevronLeftIcon className="h-4 w-4" /> Previous
        </Link>
      ) : (
        <span className="btn btn-quiet btn-sm" aria-disabled="true">
          <ChevronLeftIcon className="h-4 w-4" /> Previous
        </span>
      )}
      <ol className="hidden items-center gap-1 sm:flex">
        {windowed(current, pageCount).map((p, i) =>
          p == null ? (
            <li key={`gap-${i}`} aria-hidden className="px-1 text-muted">
              …
            </li>
          ) : (
            <li key={p}>
              {p === current ? (
                <span aria-current="page" className={`${cell} bg-ledger text-ledger-ink shadow-sm`}>
                  {p}
                </span>
              ) : (
                <Link href={href(p)} className={`${cell} text-ink-2 hover:bg-sunken hover:text-ink active:bg-rule`} aria-label={`Page ${p}`}>
                  {p}
                </Link>
              )}
            </li>
          ),
        )}
      </ol>
      <span className="num text-sm text-muted sm:hidden">
        Page {current} of {pageCount}
      </span>
      {current < pageCount ? (
        <Link href={href(current + 1)} rel="next" className="btn btn-quiet btn-sm">
          Next <ChevronRightIcon className="h-4 w-4" />
        </Link>
      ) : (
        <span className="btn btn-quiet btn-sm" aria-disabled="true">
          Next <ChevronRightIcon className="h-4 w-4" />
        </span>
      )}
    </nav>
  );
}
