import { router } from '@inertiajs/react';

type Props = {
  total: number;
  perPage: number;
  currentPage: number;
  lastPage: number;
  url?: string; // current URL path, uses window.location if omitted
  extraParams?: Record<string, string | number>;
};

export function Pagination({ total, perPage, currentPage, lastPage, url, extraParams = {} }: Props) {
  if (lastPage <= 1) return null;

  function goTo(page: number) {
    const params: Record<string, string | number> = { ...extraParams, page };
    router.get(url ?? window.location.pathname, params, { preserveScroll: true });
  }

  const start = (currentPage - 1) * perPage + 1;
  const end = Math.min(currentPage * perPage, total);

  // Build visible page numbers (first, last, current ± 2)
  const pages = new Set<number>();
  pages.add(1);
  pages.add(lastPage);
  for (let p = Math.max(1, currentPage - 2); p <= Math.min(lastPage, currentPage + 2); p++) pages.add(p);
  const sorted = Array.from(pages).sort((a, b) => a - b);

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap', marginTop: '0.75rem' }}>
      <span style={{ fontSize: '0.82rem', color: 'var(--color-text-muted)', marginLeft: 'auto' }}>
        {start}–{end} از {total}
      </span>
      <button
        type="button"
        disabled={currentPage === 1}
        onClick={() => goTo(currentPage - 1)}
        style={btnStyle(currentPage === 1)}
      >
        <i className="bi bi-chevron-right" />
      </button>

      {sorted.map((p, i) => {
        const prev = sorted[i - 1];
        return (
          <>
            {prev && p - prev > 1 && (
              <span key={`gap-${p}`} style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>…</span>
            )}
            <button
              key={p}
              type="button"
              onClick={() => goTo(p)}
              style={{
                ...btnStyle(false),
                fontWeight: p === currentPage ? 700 : 400,
                background: p === currentPage ? 'var(--color-primary)' : 'transparent',
                color: p === currentPage ? '#fff' : 'var(--color-text)',
                borderColor: p === currentPage ? 'var(--color-primary)' : 'var(--color-border)',
              }}
            >
              {p}
            </button>
          </>
        );
      })}

      <button
        type="button"
        disabled={currentPage === lastPage}
        onClick={() => goTo(currentPage + 1)}
        style={btnStyle(currentPage === lastPage)}
      >
        <i className="bi bi-chevron-left" />
      </button>
    </div>
  );
}

function btnStyle(disabled: boolean): React.CSSProperties {
  return {
    minWidth: 32,
    height: 32,
    border: '1px solid var(--color-border)',
    borderRadius: 'var(--radius-sm)',
    background: 'transparent',
    cursor: disabled ? 'not-allowed' : 'pointer',
    opacity: disabled ? 0.4 : 1,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontSize: '0.85rem',
    color: 'var(--color-text)',
    padding: '0 0.4rem',
  };
}
