"use client";

const WINDOW_SIZE = 10;
const EDGE_COUNT = 2;

type PageItem = number | "ellipsis";

function buildPageItems(current: number, total: number): PageItem[] {
  if (total <= 0) return [];
  if (total <= WINDOW_SIZE) {
    return Array.from({ length: total }, (_, i) => i + 1);
  }

  const pages = new Set<number>();

  for (let i = 1; i <= Math.min(EDGE_COUNT, total); i++) {
    pages.add(i);
  }
  for (let i = Math.max(1, total - EDGE_COUNT + 1); i <= total; i++) {
    pages.add(i);
  }

  const start = Math.max(1, current - Math.floor((WINDOW_SIZE - 1) / 2));
  const end = Math.min(total, start + WINDOW_SIZE - 1);
  const shiftedStart = Math.max(1, end - WINDOW_SIZE + 1);

  for (let i = shiftedStart; i <= end; i++) {
    pages.add(i);
  }

  const sorted = [...pages].sort((a, b) => a - b);
  const items: PageItem[] = [];

  for (let i = 0; i < sorted.length; i++) {
    const page = sorted[i];
    if (i > 0) {
      const gap = page - sorted[i - 1];
      if (gap === 2) {
        items.push(sorted[i - 1] + 1);
      } else if (gap > 2) {
        items.push("ellipsis");
      }
    }
    items.push(page);
  }

  return items;
}

export function Pagination({
  page,
  lastPage,
  onPageChange,
}: {
  page: number;
  lastPage: number;
  onPageChange: (page: number) => void;
}) {
  if (lastPage <= 1) return null;

  const items = buildPageItems(page, lastPage);

  const goTo = (next: number) => {
    if (next === page || next < 1 || next > lastPage) return;
    onPageChange(next);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <nav
      className="mt-4 flex flex-wrap items-center justify-center gap-1"
      aria-label="صفحه‌بندی"
    >
      <button
        type="button"
        disabled={page <= 1}
        onClick={() => goTo(page - 1)}
        className="rounded-lg px-3 py-1.5 text-sm font-medium text-slate-600 hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-40"
      >
        قبلی
      </button>

      {items.map((item, index) =>
        item === "ellipsis" ? (
          <span
            key={`ellipsis-${index}`}
            className="px-1.5 text-sm text-slate-500"
          >
            …
          </span>
        ) : (
          <button
            key={item}
            type="button"
            onClick={() => goTo(item)}
            aria-current={item === page ? "page" : undefined}
            className={`flex h-8 min-w-8 items-center justify-center rounded-lg px-2 text-sm ${
              item === page
                ? "bg-blue-500 font-bold text-white"
                : "font-medium text-slate-600 hover:bg-slate-100"
            }`}
          >
            {item.toLocaleString("fa-IR")}
          </button>
        ),
      )}

      <button
        type="button"
        disabled={page >= lastPage}
        onClick={() => goTo(page + 1)}
        className="rounded-lg px-3 py-1.5 text-sm font-medium text-slate-600 hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-40"
      >
        بعدی
      </button>
    </nav>
  );
}
