'use client';
import { ReactNode } from 'react';

export type Column<T> = {
  header: string;
  render: (row: T) => ReactNode;
  className?: string;
};

/** Bordered table reusing the global .table styles, with an optional quick-search box. */
export function DataTable<T>({ columns, rows, keyOf, empty = 'No records found.', caption, searchValue, onSearchChange, searchPlaceholder = 'Search…', hideSearch }: {
  columns: Column<T>[];
  rows: T[];
  keyOf: (row: T, i: number) => string | number;
  empty?: string;
  caption?: string;
  searchValue?: string;
  onSearchChange?: (v: string) => void;
  searchPlaceholder?: string;
  /** Set when the page renders its own search inside the filter bar. */
  hideSearch?: boolean;
}) {
  return (
    <div className="space-y-2">
      {onSearchChange && !hideSearch && (
        <div className="flex justify-end">
          <input
            className="input max-w-52 text-sm"
            type="search"
            placeholder={searchPlaceholder}
            aria-label={searchPlaceholder}
            value={searchValue ?? ''}
            onChange={(e) => onSearchChange(e.target.value)}
          />
        </div>
      )}
      <div className="table-wrap">
      <table className="table">
        {caption && <caption className="sr-only">{caption}</caption>}
        <thead>
          <tr>{columns.map((c, i) => <th key={i} scope="col" className={c.className}>{c.header}</th>)}</tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={keyOf(r, i)}>
              {columns.map((c, j) => <td key={j} className={c.className}>{c.render(r)}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
      {rows.length === 0 && <p className="text-sm text-center px-3 py-4" style={{ color: 'var(--muted)' }}>{empty}</p>}
      </div>
    </div>
  );
}

/** Server- or client-side pager: "Showing X–Y of Z" with Prev/Next. */
export function Pagination({ page, total, limit, onPage }: {
  page: number; total: number; limit: number; onPage: (p: number) => void;
}) {
  const pages = Math.max(1, Math.ceil(total / limit));
  const from = total === 0 ? 0 : (page - 1) * limit + 1;
  const to = Math.min(total, page * limit);
  return (
    <div className="flex flex-wrap items-center gap-2">
      <p className="text-xs mr-auto" style={{ color: 'var(--muted)' }} aria-live="polite">
        Showing {from}–{to} of {total}
      </p>
      <button type="button" className="btn-ghost btn-sm" disabled={page <= 1} onClick={() => onPage(page - 1)}>‹ Prev</button>
      <span className="text-xs" style={{ color: 'var(--muted)' }}>Page {page} of {pages}</span>
      <button type="button" className="btn-ghost btn-sm" disabled={page >= pages} onClick={() => onPage(page + 1)}>Next ›</button>
    </div>
  );
}
