"use client";

import { ChevronLeft, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useI18n, useT } from "@/i18n";
import { cn } from "@/lib/cn";

/**
 * Pagination for the ApiResponder envelope. `total` is the LAST page number,
 * `records` the total row count.
 */
export function Pagination({
  page,
  totalPages,
  records,
  onPageChange,
}: {
  page: number;
  totalPages: number;
  records: number;
  onPageChange: (page: number) => void;
}) {
  const t = useT();
  const { dir } = useI18n();
  const ArrowIcon = dir === "rtl" ? ChevronRight : ChevronLeft;
  const from = records === 0 ? 0 : (page - 1) * 10 + 1;
  const to = Math.min(page * 10, records);

  return (
    <div className="flex flex-col items-center justify-between gap-3 px-5 py-3 sm:flex-row">
      <p className="text-xs text-muted-foreground">
        {t("common.showing")} <span className="numeric">{from} – {to}</span>{" "}
        {t("common.outOf")} <span className="numeric">{records.toLocaleString()}</span>
      </p>
      <div className="flex items-center gap-1">
        <Button
          variant="outline"
          size="sm"
          onClick={() => onPageChange(page - 1)}
          disabled={page <= 1}
          aria-label={t("common.previous")}
        >
          <ArrowIcon className="h-3.5 w-3.5" aria-hidden />
        </Button>
        <span className="numeric px-3 text-xs font-medium text-muted-foreground">
          {t("common.page")} {page} {t("common.outOf")} {Math.max(totalPages, 1)}
        </span>
        <Button
          variant="outline"
          size="sm"
          onClick={() => onPageChange(page + 1)}
          disabled={page >= Math.max(totalPages, 1)}
          aria-label={t("common.next")}
        >
          <ChevronRight className={cn("h-3.5 w-3.5", dir === "rtl" && "rotate-180")} aria-hidden />
        </Button>
      </div>
    </div>
  );
}