import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";

export function usePagination<T>(rows: T[], pageSize = 12) {
  const [page, setPage] = useState(1);
  const totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
  const safePage = Math.min(page, totalPages);
  const paged = useMemo(
    () => rows.slice((safePage - 1) * pageSize, safePage * pageSize),
    [rows, safePage, pageSize],
  );
  return { page: safePage, setPage, totalPages, paged, total: rows.length };
}

export function Pager({
  page,
  totalPages,
  onChange,
  total,
  className,
}: {
  page: number;
  totalPages: number;
  onChange: (p: number) => void;
  total?: number;
  className?: string;
}) {
  if (totalPages <= 1) return null;
  const visible = pageWindow(page, totalPages);
  return (
    <div className={`mt-4 flex items-center justify-between text-xs text-muted-foreground ${className ?? ""}`}>
      {total != null ? <div>{total.toLocaleString()} records</div> : <span />}
      <div className="flex items-center gap-1">
        <Button size="icon" variant="outline" disabled={page === 1} onClick={() => onChange(page - 1)}>
          <ChevronLeft className="h-4 w-4" />
        </Button>
        {visible.map((p, i) =>
          p === "…" ? (
            <span key={`e-${i}`} className="px-1.5">…</span>
          ) : (
            <Button
              key={p}
              size="sm"
              variant={p === page ? "default" : "outline"}
              className={p === page ? "gradient-primary text-primary-foreground" : ""}
              onClick={() => onChange(p as number)}
            >
              {p}
            </Button>
          ),
        )}
        <Button size="icon" variant="outline" disabled={page === totalPages} onClick={() => onChange(page + 1)}>
          <ChevronRight className="h-4 w-4" />
        </Button>
      </div>
    </div>
  );
}

function pageWindow(current: number, total: number): (number | "…")[] {
  const out: (number | "…")[] = [];
  const push = (n: number | "…") => out.push(n);
  const window = 1;
  for (let i = 1; i <= total; i++) {
    if (i === 1 || i === total || (i >= current - window && i <= current + window)) {
      push(i);
    } else if (out[out.length - 1] !== "…") {
      push("…");
    }
  }
  return out;
}