import { HTMLAttributes } from 'react';
import { cn } from '../lib/cn';

export interface PaginationProps extends HTMLAttributes<HTMLElement> {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  siblingCount?: number;
}

type Item = number | 'ellipsis-l' | 'ellipsis-r';

function buildPages(current: number, total: number, sibling: number): Item[] {
  if (total <= 7) {
    return Array.from({ length: total }, (_, i) => i + 1);
  }
  const items: Item[] = [];
  const leftBoundary = Math.max(2, current - sibling);
  const rightBoundary = Math.min(total - 1, current + sibling);

  items.push(1);
  if (leftBoundary > 2) items.push('ellipsis-l');
  for (let p = leftBoundary; p <= rightBoundary; p++) items.push(p);
  if (rightBoundary < total - 1) items.push('ellipsis-r');
  items.push(total);
  return items;
}

const btnBase =
  'inline-flex items-center justify-center min-w-9 h-9 px-3 rounded-lg text-sm border transition-colors';

export function Pagination({
  currentPage,
  totalPages,
  onPageChange,
  siblingCount = 1,
  className,
  ...rest
}: PaginationProps) {
  if (totalPages <= 0) return null;
  const pages = buildPages(currentPage, totalPages, siblingCount);
  const prevDisabled = currentPage <= 1;
  const nextDisabled = currentPage >= totalPages;

  return (
    <nav
      aria-label="Pagination"
      className={cn('flex items-center gap-1.5', className)}
      {...rest}
    >
      <button
        type="button"
        disabled={prevDisabled}
        onClick={() => !prevDisabled && onPageChange(currentPage - 1)}
        aria-label="Previous page"
        className={cn(
          btnBase,
          'bg-surface border-border text-text-2 hover:text-text hover:border-text-3',
          prevDisabled && 'opacity-40 cursor-not-allowed',
        )}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
          <polyline points="15 18 9 12 15 6" />
        </svg>
      </button>

      {pages.map((p, idx) =>
        typeof p === 'string' ? (
          <span
            key={`${p}-${idx}`}
            aria-hidden="true"
            className="inline-flex items-center justify-center min-w-9 h-9 text-sm text-text-3"
          >
            …
          </span>
        ) : (
          <button
            key={p}
            type="button"
            aria-current={p === currentPage ? 'page' : undefined}
            onClick={() => onPageChange(p)}
            className={cn(
              btnBase,
              'tab-num',
              p === currentPage
                ? 'bg-primary border-primary text-primary-on'
                : 'bg-surface border-border text-text-2 hover:text-text hover:border-text-3',
            )}
          >
            {p}
          </button>
        ),
      )}

      <button
        type="button"
        disabled={nextDisabled}
        onClick={() => !nextDisabled && onPageChange(currentPage + 1)}
        aria-label="Next page"
        className={cn(
          btnBase,
          'bg-surface border-border text-text-2 hover:text-text hover:border-text-3',
          nextDisabled && 'opacity-40 cursor-not-allowed',
        )}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
          <polyline points="9 18 15 12 9 6" />
        </svg>
      </button>
    </nav>
  );
}
