'use client'

export interface PaginationProps {
  page: number
  perPage: number
  total: number
  onPageChange: (page: number) => void
  onPerPageChange: (perPage: number) => void
}

export function Pagination({
  page,
  perPage,
  total,
  onPageChange,
  onPerPageChange,
}: PaginationProps) {
  const totalPages = Math.max(1, Math.ceil(total / perPage))
  const start = (page - 1) * perPage + 1
  const end = Math.min(page * perPage, total)

  function pageNumbers(): (number | 'ellipsis')[] {
    const pages: (number | 'ellipsis')[] = []
    for (let i = 1; i <= totalPages; i++) {
      if (i === 1 || i === totalPages || Math.abs(i - page) <= 1) {
        pages.push(i)
      } else if (pages[pages.length - 1] !== 'ellipsis') {
        pages.push('ellipsis')
      }
    }
    return pages
  }

  return (
    <div className="flex items-center justify-between text-sm">
      <span className="text-[var(--muted-foreground)]">
        {start}–{end} of {total} results
      </span>

      <div className="flex items-center gap-2">
        <select
          value={perPage}
          onChange={(e) => {
            onPerPageChange(Number(e.target.value))
            onPageChange(1)
          }}
          className="rounded-md border border-[var(--border)] bg-[var(--input-background)] px-2 py-1 text-sm"
        >
          {[10, 25, 50, 100].map((n) => (
            <option key={n} value={n}>
              {n} / page
            </option>
          ))}
        </select>

        <nav className="flex items-center gap-1">
          <button
            onClick={() => onPageChange(page - 1)}
            disabled={page <= 1}
            className="rounded-md px-2 py-1 hover:bg-[var(--accent)] disabled:opacity-50"
          >
            Prev
          </button>
          {pageNumbers().map((p, i) =>
            p === 'ellipsis' ? (
              <span key={`e${i}`} className="px-1 text-[var(--muted-foreground)]">
                …
              </span>
            ) : (
              <button
                key={p}
                onClick={() => onPageChange(p)}
                className={`min-w-[2rem] rounded-md px-2 py-1 ${
                  p === page
                    ? 'bg-[var(--primary)] text-[var(--primary-foreground)]'
                    : 'hover:bg-[var(--accent)]'
                }`}
              >
                {p}
              </button>
            ),
          )}
          <button
            onClick={() => onPageChange(page + 1)}
            disabled={page >= totalPages}
            className="rounded-md px-2 py-1 hover:bg-[var(--accent)] disabled:opacity-50"
          >
            Next
          </button>
        </nav>
      </div>
    </div>
  )
}
