'use client';

import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
import type { ReactNode } from 'react';

import { Select } from '@/components/ui/input';
import { cn } from '@/lib/utils';

/** Page numbers with ellipses, e.g. 1 … 4 5 6 … 20. */
const pageList = (page: number, total: number): Array<number | 'gap'> => {
  if (total <= 7) return Array.from({ length: total }, (_, index) => index + 1);
  const pages = new Set([1, total, page, page - 1, page + 1]);
  const sorted = [...pages].filter((value) => value >= 1 && value <= total).sort((a, b) => a - b);
  const result: Array<number | 'gap'> = [];
  sorted.forEach((value, index) => {
    const previous = sorted[index - 1];
    if (previous !== undefined && value - previous > 1) result.push('gap');
    result.push(value);
  });
  return result;
};

function IconButton({ label, disabled, onClick, children }: { label: string; disabled: boolean; onClick: () => void; children: ReactNode }) {
  return (
    <button
      type="button"
      aria-label={label}
      disabled={disabled}
      onClick={onClick}
      className="grid h-9 w-9 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40"
    >
      {children}
    </button>
  );
}

export function Pagination({
  page,
  totalPages,
  total,
  pageSize,
  onPage,
  onPageSize,
  noun = 'results',
  pageSizes = [20, 50, 100],
}: {
  page: number;
  totalPages: number;
  total: number;
  pageSize: number;
  onPage: (page: number) => void;
  onPageSize?: (pageSize: number) => void;
  noun?: string;
  pageSizes?: number[];
}) {
  const pages = Math.max(1, totalPages);
  const from = total === 0 ? 0 : (page - 1) * pageSize + 1;
  const to = Math.min(total, page * pageSize);
  return (
    <nav aria-label="Pagination" className="flex flex-col-reverse items-center justify-between gap-3 sm:flex-row">
      <div className="flex items-center gap-3 text-small text-muted-foreground">
        {onPageSize === undefined ? null : (
          <label className="inline-flex items-center gap-2">
            <span className="sr-only sm:not-sr-only">Rows</span>
            <Select className="h-9 min-h-9 w-[5.5rem] py-0 text-small" value={String(pageSize)} onChange={(event) => onPageSize(Number(event.target.value))}>
              {pageSizes.map((size) => (
                <option key={size} value={size}>
                  {size}
                </option>
              ))}
            </Select>
          </label>
        )}
        <p className="tabular-nums" aria-live="polite">
          Showing {from.toLocaleString()} to {to.toLocaleString()} of {total.toLocaleString()} {noun}
        </p>
      </div>
      <div className="flex items-center gap-0.5">
        <IconButton label="First page" disabled={page <= 1} onClick={() => onPage(1)}>
          <ChevronsLeft className="h-4 w-4" aria-hidden="true" />
        </IconButton>
        <IconButton label="Previous page" disabled={page <= 1} onClick={() => onPage(page - 1)}>
          <ChevronLeft className="h-4 w-4" aria-hidden="true" />
        </IconButton>
        <span className="hidden items-center gap-0.5 sm:flex">
          {pageList(page, pages).map((value, index) =>
            value === 'gap' ? (
              <span key={`gap-${index}`} className="grid h-9 w-7 place-items-center text-subtle-foreground" aria-hidden="true">
                …
              </span>
            ) : (
              <button
                key={value}
                type="button"
                aria-label={`Page ${value}`}
                aria-current={value === page ? 'page' : undefined}
                onClick={() => onPage(value)}
                className={cn(
                  'grid h-9 min-w-9 place-items-center rounded-md px-2 text-small font-semibold tabular-nums transition-colors',
                  value === page ? 'bg-primary-soft text-primary' : 'text-muted-foreground hover:bg-surface-muted hover:text-foreground',
                )}
              >
                {value}
              </button>
            ),
          )}
        </span>
        <span className="px-2 text-small tabular-nums text-muted-foreground sm:hidden">
          {page} / {pages}
        </span>
        <IconButton label="Next page" disabled={page >= pages} onClick={() => onPage(page + 1)}>
          <ChevronRight className="h-4 w-4" aria-hidden="true" />
        </IconButton>
        <IconButton label="Last page" disabled={page >= pages} onClick={() => onPage(pages)}>
          <ChevronsRight className="h-4 w-4" aria-hidden="true" />
        </IconButton>
      </div>
    </nav>
  );
}
