// src/v2/components/ui/Pagination.jsx
// Page navigation bar rendered below DataTable (and any paginated list).
//
// Props:
//   page        — number — current page (1-based)
//   pageSize    — number — rows per page
//   total       — number — total record count
//   onPageChange— (page: number) => void
//   onSizeChange— (size: number) => void  (optional — shows per-page selector)
//   pageSizes   — number[]               (default: [20, 50, 100])
//   className   — extra wrapper classes
//
// Styles live in src/v2/styles/components.css (.pagination*)

const DEFAULT_PAGE_SIZES = [20, 50, 100]
const MAX_VISIBLE_PAGES  = 7 // pages shown before collapsing to ellipsis

function buildPageList(page, totalPages) {
  if (totalPages <= MAX_VISIBLE_PAGES) {
    return Array.from({ length: totalPages }, (_, i) => i + 1)
  }
  const pages = new Set([1, totalPages, page])
  // Show 2 neighbours on each side of current page
  for (let i = Math.max(2, page - 2); i <= Math.min(totalPages - 1, page + 2); i++) {
    pages.add(i)
  }
  const sorted = [...pages].sort((a, b) => a - b)
  const result = []
  let prev = null
  for (const p of sorted) {
    if (prev !== null && p - prev > 1) result.push('…')
    result.push(p)
    prev = p
  }
  return result
}

export default function Pagination({
  page = 1,
  pageSize = 20,
  total = 0,
  onPageChange,
  onSizeChange,
  pageSizes = DEFAULT_PAGE_SIZES,
  className = '',
}) {
  const totalPages = Math.max(1, Math.ceil(total / pageSize))
  const from       = total === 0 ? 0 : (page - 1) * pageSize + 1
  const to         = Math.min(page * pageSize, total)
  const pages      = buildPageList(page, totalPages)

  return (
    <div className={`pagination ${className}`}>
      {/* Row count summary */}
      <span className="pagination-info">
        {total === 0
          ? 'No results'
          : `${from}–${to} of ${total.toLocaleString()}`}
      </span>

      <div className="flex items-center gap-3">
        {/* Per-page selector */}
        {onSizeChange && (
          <div className="pagination-info flex items-center gap-2">
            <span>Rows</span>
            <div className="pagination-size-group" role="group" aria-label="Rows per page">
              {pageSizes.map((s) => (
                <button
                  key={s}
                  className={`pagination-size-btn${s === pageSize ? ' pagination-size-btn--active' : ''}`}
                  onClick={() => { if (s !== pageSize) onSizeChange(s) }}
                  aria-pressed={s === pageSize}
                  aria-label={`${s} rows per page`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Page buttons */}
        <div className="pagination-controls">
          {/* Previous */}
          <button
            className="pagination-btn"
            onClick={() => onPageChange?.(page - 1)}
            disabled={page <= 1}
            aria-label="Previous page"
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M10 12L6 8l4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>

          {pages.map((p, i) =>
            p === '…' ? (
              <span
                key={`ellipsis-${i}`}
                className="pagination-btn"
                style={{ cursor: 'default', color: 'var(--color-text-muted)' }}
                aria-hidden="true"
              >
                …
              </span>
            ) : (
              <button
                key={p}
                className={`pagination-btn ${p === page ? 'active' : ''}`}
                onClick={() => onPageChange?.(p)}
                aria-label={`Page ${p}`}
                aria-current={p === page ? 'page' : undefined}
              >
                {p}
              </button>
            )
          )}

          {/* Next */}
          <button
            className="pagination-btn"
            onClick={() => onPageChange?.(page + 1)}
            disabled={page >= totalPages}
            aria-label="Next page"
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M6 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  )
}
