"use client";

import { useMemo } from "react";
import { Button, Spinner } from "react-bootstrap";
import { ChevronLeft, ChevronRight } from "react-bootstrap-icons";

type PaginationProps = {
  page: number;
  totalPages: number;
  loading?: boolean;
  /** Build href for a given page number (for SSR/link fallback) */
  buildHref: (p: number) => string;
  onPageChange: (p: number) => void;
};

export default function Pagination({
  page,
  totalPages,
  loading,
  buildHref,
  onPageChange,
}: PaginationProps) {
  const canPrev = page > 1;
  const canNext = page < totalPages;

  const prevHref = useMemo(() => buildHref(Math.max(1, page - 1)), [buildHref, page]);
  const nextHref = useMemo(() => buildHref(Math.min(totalPages, page + 1)), [buildHref, page, totalPages]);

  return (
    <div className="d-flex align-items-center gap-2 mt-4">
      <span className={loading ? "text-secondary" : ""}>
        Page {page} / {totalPages}
      </span>
      {loading && (
        <Spinner animation="border" size="sm" variant="secondary" role="status" />
      )}
      <div className="ms-auto d-flex gap-2">
        <Button
          as="a"
          variant="outline-secondary"
          href={prevHref}
          disabled={!canPrev}
          onClick={(e: React.MouseEvent) => {
            if (!canPrev) return;
            e.preventDefault();
            onPageChange(page - 1);
          }}
        >
          <ChevronLeft size={14} /> Prev
        </Button>
        <Button
          as="a"
          variant="outline-secondary"
          href={nextHref}
          disabled={!canNext}
          onClick={(e: React.MouseEvent) => {
            if (!canNext) return;
            e.preventDefault();
            onPageChange(page + 1);
          }}
        >
          Next <ChevronRight size={14} />
        </Button>
      </div>
    </div>
  );
}
