import { Link } from '@inertiajs/react';

type PaginationProps = {
  currentPage: number;
  lastPage: number;
  routeName: string;
  perPage?: number;
};

function buildPages(currentPage: number, lastPage: number) {
  const delta = 2;
  const start = Math.max(1, currentPage - delta);
  const end = Math.min(lastPage, currentPage + delta);
  const pages: number[] = [];

  for (let p = start; p <= end; p++) {
    pages.push(p);
  }

  return pages;
}

export default function Pagination({ currentPage, lastPage, routeName, perPage }: PaginationProps) {
  if (lastPage <= 1) return null;

  const pages = buildPages(currentPage, lastPage);
  const prevPage = currentPage > 1 ? currentPage - 1 : null;
  const nextPage = currentPage < lastPage ? currentPage + 1 : null;

  const makeHref = (page: number) =>
    route(routeName, {
      ...(perPage ? { per_page: perPage } : {}),
      page,
    });

  return (
    <nav className="pagination">
      {prevPage ? (
        <Link className="button button--icon pagination-control" href={makeHref(prevPage)} preserveScroll preserveState>
          <i className="icon-arrowLeft pagination-controlIcon"></i>
        </Link>
      ) : (
        <span className="button button--icon pagination-control" aria-disabled="true">
          <i className="icon-arrowLeft pagination-controlIcon"></i>
        </span>
      )}

      <div className="pagination-pages">
        {pages.map((page) => (
          <Link
            key={page}
            className={`pagination-page${page === currentPage ? ' pagination-active' : ''}`}
            href={makeHref(page)}
            preserveScroll
            preserveState
          >
            {page}
          </Link>
        ))}
      </div>

      {nextPage ? (
        <Link className="button button--icon pagination-control" href={makeHref(nextPage)} preserveScroll preserveState>
          <i className="icon-arrowRight pagination-controlIcon"></i>
        </Link>
      ) : (
        <span className="button button--icon pagination-control" aria-disabled="true">
          <i className="icon-arrowRight pagination-controlIcon"></i>
        </span>
      )}
    </nav>
  );
}