"use client";

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

interface PageNumbersProps {
  page: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  siblings?: number;
}

/**
 * Builds the list of page slots to render: first, current ± `siblings`, last,
 * with "ellipsis" markers where pages are collapsed.
 */
function getPageNumbers(
  current: number,
  totalPages: number,
  siblings: number,
): (number | "ellipsis")[] {
  const totalSlots = 5 + siblings * 2;
  if (totalPages <= totalSlots) {
    return Array.from({ length: totalPages }, (_, i) => i + 1);
  }

  const leftSibling = Math.max(current - siblings, 1);
  const rightSibling = Math.min(current + siblings, totalPages);
  const showLeftEllipsis = leftSibling > 2;
  const showRightEllipsis = rightSibling < totalPages - 1;

  if (!showLeftEllipsis && showRightEllipsis) {
    const leftCount = 3 + siblings * 2;
    return [
      ...Array.from({ length: leftCount }, (_, i) => i + 1),
      "ellipsis",
      totalPages,
    ];
  }

  if (showLeftEllipsis && !showRightEllipsis) {
    const rightCount = 3 + siblings * 2;
    return [
      1,
      "ellipsis",
      ...Array.from(
        { length: rightCount },
        (_, i) => totalPages - rightCount + 1 + i,
      ),
    ];
  }

  return [
    1,
    "ellipsis",
    ...Array.from(
      { length: rightSibling - leftSibling + 1 },
      (_, i) => leftSibling + i,
    ),
    "ellipsis",
    totalPages,
  ];
}

export function PageNumbers({
  page,
  totalPages,
  onPageChange,
  siblings = 1,
}: PageNumbersProps) {
  if (totalPages <= 1) return null;

  return (
    <div className="flex items-center gap-1">
      <Button
        variant="outline"
        size="sm"
        onClick={() => onPageChange(Math.max(1, page - 1))}
        disabled={page === 1}
        className="h-7 w-7 p-0"
        aria-label="Page précédente"
      >
        <ChevronLeft className="w-3.5 h-3.5" />
      </Button>
      {getPageNumbers(page, totalPages, siblings).map((p, idx) =>
        p === "ellipsis" ? (
          <span
            key={`ellipsis-${idx}`}
            className="text-xs text-muted-foreground px-1 select-none"
            aria-hidden
          >
            …
          </span>
        ) : (
          <Button
            key={p}
            variant={p === page ? "default" : "outline"}
            size="sm"
            onClick={() => onPageChange(p)}
            aria-current={p === page ? "page" : undefined}
            className="h-7 min-w-7 px-2 text-xs font-medium"
          >
            {p}
          </Button>
        ),
      )}
      <Button
        variant="outline"
        size="sm"
        onClick={() => onPageChange(Math.min(totalPages, page + 1))}
        disabled={page === totalPages}
        className="h-7 w-7 p-0"
        aria-label="Page suivante"
      >
        <ChevronRight className="w-3.5 h-3.5" />
      </Button>
    </div>
  );
}
