import React, { useEffect, useMemo, useState } from "react";

const clampInt = (v, min, max) => {
  const n = Number.parseInt(String(v || ""), 10);
  if (!Number.isFinite(n)) return min;
  return Math.max(min, Math.min(max, n));
};

function readSessionInt(key, fallback) {
  try {
    const raw = sessionStorage.getItem(key);
    const n = Number.parseInt(raw, 10);
    return Number.isFinite(n) ? n : fallback;
  } catch {
    return fallback;
  }
}

function writeSessionInt(key, value) {
  try {
    sessionStorage.setItem(key, String(value));
  } catch {}
}

export default function PaginationControls({
  total = 0,
  page,
  onPageChange,
  pageSize,
  onPageSizeChange,
  sessionKey = "storage.pageSize",
  defaultPageSize = 8,
  minPageSize = 1,
  maxPageSize = 200,
  className = "",
  label = "نمایش",
}) {
  const totalItems = Math.max(0, Number(total) || 0);

  // اگر parent pageSize نداد، از session بخون (ولی معمولاً parent می‌ده)
  const initialSize = useMemo(() => {
    if (Number.isFinite(pageSize) && pageSize > 0) return pageSize;
    return readSessionInt(sessionKey, defaultPageSize);
  }, [pageSize, sessionKey, defaultPageSize]);

  const [draftSize, setDraftSize] = useState(String(initialSize));

  const size = clampInt(pageSize ?? initialSize, minPageSize, maxPageSize);
  const totalPages = Math.max(1, Math.ceil(totalItems / size));
  const currentPage = clampInt(page ?? 1, 1, totalPages);

  // همگام‌سازی draft با pageSize فعلی
  useEffect(() => {
    setDraftSize(String(size));
  }, [size]);

  const canPrev = currentPage > 1;
  const canNext = currentPage < totalPages;

  const applySize = () => {
    const nextSize = clampInt(draftSize, minPageSize, maxPageSize);
    writeSessionInt(sessionKey, nextSize);
    onPageSizeChange?.(nextSize);
    // وقتی سایز عوض می‌شه بهتره برگردیم صفحه 1
    onPageChange?.(1);
  };

  return (
    <div
      className={[
        "flex flex-wrap items-center shadow justify-between gap-3 rounded-2xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-[#16325B]/50 p-3",
        className,
      ].join(" ")}
    >
      {/* left: page info */}
      <div className="text-xs sm:w-60 text-black/60 dark:text-white/70">
        صفحه <b className="dark:text-white text-black">{currentPage}</b> از{" "}
        <b className="dark:text-white text-black">{totalPages}</b> • کل{" "}
        <b className="dark:text-white text-black">{totalItems}</b>
      </div>

      {/* center: prev/next */}
      <div className="flex items-center gap-2">
        <button
          type="button"
          onClick={() => canPrev && onPageChange?.(currentPage - 1)}
          disabled={!canPrev}
          className="px-3 py-2 rounded-xl border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10 disabled:opacity-50 disabled:pointer-events-none text-xs"
        >
          قبلی
        </button>

        <button
          type="button"
          onClick={() => canNext && onPageChange?.(currentPage + 1)}
          disabled={!canNext}
          className="px-3 py-2 rounded-xl border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10 disabled:opacity-50 disabled:pointer-events-none text-xs"
        >
          بعدی
        </button>
      </div>

      {/* right: page size */}
      <div className="flex sm:w-60 items-center sm:justify-end gap-2 text-xs">
        <span className="text-black/60 dark:text-white/70">{label} در هر صفحه:</span>

        <input
          value={draftSize}
          onChange={(e) => setDraftSize(e.target.value)}
          inputMode="numeric"
          className="w-16 rounded-xl border text-center border-black/10 dark:border-white/10 bg-white dark:bg-[#001F3F] px-2 py-1.5 outline-none dark:text-white text-black text-xs"
        />

        <button
          type="button"
          onClick={applySize}
          className="px-3 py-2 rounded-xl bg-white shadow dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 hover:bg-black/20 dark:hover:bg-white/10 text-xs"
        >
          اعمال
        </button>
      </div>
    </div>
  );
}
