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

import { Button } from '@/Components/ui/button';

interface PaginationLink {
  url: string | null;
  label: string;
  active: boolean;
}

interface InertiaPaginationProps {
  links: PaginationLink[];
  currentPage?: number;
  lastPage?: number;
  perPage?: number;
  total?: number;
}

export default function InertiaPagination({
  links,
  currentPage = 1,
  lastPage = 1,
  perPage,
  total,
}: InertiaPaginationProps) {
  if ((lastPage ?? 1) <= 1) return null;

  const prevLink = links[0];
  const nextLink = links[links.length - 1];

  // Calculate range of items shown
  let itemsRangeText: string | null = null;
  if (perPage && total && currentPage != null) {
    const from = (currentPage - 1) * perPage + 1;
    const to = Math.min(currentPage * perPage, total);
    itemsRangeText = `Showing ${from}–${to} of ${total} items`;
  }

  return (
    <nav aria-label="Pagination" className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between pt-4">
      <p className="text-sm text-muted-foreground">
        {itemsRangeText ? itemsRangeText : `Page ${currentPage} of ${lastPage}`}
      </p>
      <div className="flex gap-2">
        {prevLink?.url ? (
          <Button variant="outline" size="sm" asChild>
            <Link href={prevLink.url}>Previous</Link>
          </Button>
        ) : (
          <Button variant="outline" size="sm" disabled>
            Previous
          </Button>
        )}
        {nextLink?.url ? (
          <Button variant="outline" size="sm" asChild>
            <Link href={nextLink.url}>Next</Link>
          </Button>
        ) : (
          <Button variant="outline" size="sm" disabled>
            Next
          </Button>
        )}
      </div>
    </nav>
  );
}
