import * as React from 'react';

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

/**
 * Data table primitives.
 *
 * Back-office views are dense but must stay readable (SPEC.md §6). The wrapper
 * scrolls horizontally on small screens rather than letting the page overflow,
 * and a caption is required so screen-reader users know what the table lists.
 */

export function TableWrapper({
  className,
  ...props
}: React.HTMLAttributes<HTMLDivElement>): React.JSX.Element {
  return (
    <div
      className={cn(
        'glass overflow-x-auto rounded-[var(--radius-card)] border',
        className,
      )}
      {...props}
    />
  );
}

export function Table({
  className,
  caption,
  children,
  ...props
}: React.TableHTMLAttributes<HTMLTableElement> & { caption: string }): React.JSX.Element {
  return (
    <table className={cn('w-full border-collapse text-sm', className)} {...props}>
      <caption className="sr-only">{caption}</caption>
      {children}
    </table>
  );
}

export function THead({
  className,
  ...props
}: React.HTMLAttributes<HTMLTableSectionElement>): React.JSX.Element {
  return <thead className={cn('bg-glass-sunken', className)} {...props} />;
}

export function TBody({
  className,
  ...props
}: React.HTMLAttributes<HTMLTableSectionElement>): React.JSX.Element {
  return <tbody className={cn('divide-y divide-border', className)} {...props} />;
}

export function TR({
  className,
  ...props
}: React.HTMLAttributes<HTMLTableRowElement>): React.JSX.Element {
  return <tr className={cn('transition-colors hover:bg-surface-muted/60', className)} {...props} />;
}

export function TH({
  className,
  align = 'left',
  ...props
}: React.ThHTMLAttributes<HTMLTableCellElement> & {
  align?: 'left' | 'right' | 'center';
}): React.JSX.Element {
  return (
    <th
      scope="col"
      className={cn(
        'whitespace-nowrap border-b border-border px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-ink-muted',
        align === 'right' && 'text-right',
        align === 'center' && 'text-center',
        align === 'left' && 'text-left',
        className,
      )}
      {...props}
    />
  );
}

export function TD({
  className,
  align = 'left',
  numeric,
  ...props
}: React.TdHTMLAttributes<HTMLTableCellElement> & {
  align?: 'left' | 'right' | 'center';
  /** Right-aligns and tabular-figures the cell, for money and counts. */
  numeric?: boolean;
}): React.JSX.Element {
  return (
    <td
      className={cn(
        'px-4 py-2.5 align-middle text-ink',
        (align === 'right' || numeric) && 'text-right',
        align === 'center' && 'text-center',
        numeric && 'tabular-nums',
        className,
      )}
      {...props}
    />
  );
}

/* -------------------------------------------------------------------------- */
/* Pagination                                                                 */
/* -------------------------------------------------------------------------- */

export interface PaginationProps {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
  /** Builds the href for a page; keeps pagination usable without JavaScript. */
  buildHref: (page: number) => string;
  className?: string;
}

export function Pagination({
  page,
  pageSize,
  total,
  totalPages,
  buildHref,
  className,
}: PaginationProps): React.JSX.Element | null {
  if (total === 0) return null;

  const first = (page - 1) * pageSize + 1;
  const last = Math.min(page * pageSize, total);

  const linkClass = cn(
    'inline-flex h-8 items-center rounded-[var(--radius-control)] border border-border-strong',
    'bg-white px-3 text-sm text-ink transition-colors hover:bg-surface-muted',
  );
  const disabledClass = 'pointer-events-none opacity-45';

  return (
    <nav
      aria-label="Pagination"
      className={cn('flex flex-wrap items-center justify-between gap-3 px-1 py-3', className)}
    >
      <p className="text-sm text-ink-muted">
        Showing <span className="font-medium text-ink tabular-nums">{first}</span>–
        <span className="font-medium text-ink tabular-nums">{last}</span> of{' '}
        <span className="font-medium text-ink tabular-nums">{total}</span>
      </p>

      <div className="flex items-center gap-2">
        <a
          href={buildHref(page - 1)}
          className={cn(linkClass, page <= 1 && disabledClass)}
          aria-disabled={page <= 1}
          rel="prev"
        >
          Previous
        </a>
        <span className="text-sm text-ink-muted tabular-nums" aria-current="page">
          Page {page} of {totalPages}
        </span>
        <a
          href={buildHref(page + 1)}
          className={cn(linkClass, page >= totalPages && disabledClass)}
          aria-disabled={page >= totalPages}
          rel="next"
        >
          Next
        </a>
      </div>
    </nav>
  );
}
