import { ReactNode } from 'react';
import {
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableSortLabel,
  Typography,
} from '@mui/material';

export type AdminSortDirection = 'asc' | 'desc';

export interface AdminTableColumn<T> {
  /** Stable column key (also `data-col` for tests). */
  key: string;
  /** Already-translated header label. */
  header: string;
  /** Cell renderer for a row. */
  render: (row: T) => ReactNode;
  /** Optional cell alignment (defaults to `inherit`, which follows text direction — RTL-safe). */
  align?: 'inherit' | 'left' | 'center' | 'right';
  width?: number | string;
  /** Floor width so a narrow value (a status chip, a short date) doesn't collapse the column on scroll. */
  minWidth?: number | string;
  /** Marks the column as a server-param sort target — renders a `TableSortLabel`; requires `onSortChange`. */
  sortable?: boolean;
}

export interface AdminSortState {
  key: string;
  direction: AdminSortDirection;
}

export interface AdminDataTableProps<T> {
  columns: AdminTableColumn<T>[];
  rows: T[];
  getRowKey: (row: T) => string | number;
  onRowClick?: (row: T) => void;
  dense?: boolean;
  /** Accessible table name (already translated). */
  ariaLabel?: string;
  /** Bounds the table to a scrollable viewport with a header that stays visible while scrolling — opt in
   * on long worklists (the filter object stays the query key; sort/page are just more of it, per 3.1). */
  stickyHeader?: boolean;
  /** `stickyHeader`'s scroll viewport height. */
  stickyMaxHeight?: number | string;
  /** The currently active server-param sort, or `null`/absent when unsorted. */
  sort?: AdminSortState | null;
  /** Fired with a sortable column's `key` when its header is clicked — the caller owns the 3-state cycle. */
  onSortChange?: (key: string) => void;
  /** Already-translated footer line («نمایش ۱–۲۰ از ۱۲۴») — rendered only when passed; every caller already
   * holds `total` from its paginated query, so this mirrors `AdminPager`'s pre-translated-string convention. */
  footer?: string;
}

/**
 * The shared dense worklist table for the backoffice. Columns are declared with a typed `render`; the
 * whole table scrolls horizontally inside its own container so a wide worklist never breaks the page layout
 * (a hard responsive rule). Rows are optionally clickable (a queue row → its case). Header/cell alignment
 * defaults to `inherit` so it follows the active text direction (RTL-safe). Colors come from the palette.
 * v2 (ui-phase-11) adds optional per-column server-param sort, a sticky-header scroll viewport for long
 * pages, per-column `minWidth`, and a results footer line.
 * @component AdminDataTable
 */
function AdminDataTable<T>({
  columns,
  rows,
  getRowKey,
  onRowClick,
  dense = true,
  ariaLabel,
  stickyHeader = false,
  stickyMaxHeight = 640,
  sort,
  onSortChange,
  footer,
}: AdminDataTableProps<T>) {
  return (
    <>
      <TableContainer
        component={Paper}
        elevation={0}
        sx={{
          border: '1px solid',
          borderColor: 'divider',
          borderRadius: 'var(--bal-radius-md)',
          overflowX: 'auto',
          ...(stickyHeader ? { maxHeight: stickyMaxHeight, overflowY: 'auto' } : {}),
        }}
      >
        <Table stickyHeader={stickyHeader} size={dense ? 'small' : 'medium'} aria-label={ariaLabel} sx={{ minWidth: 640 }}>
          <TableHead>
            <TableRow sx={{ '& th': { fontWeight: 700, color: 'text.secondary', bgcolor: 'action.hover' } }}>
              {columns.map((col) => (
                <TableCell
                  key={col.key}
                  align={col.align ?? 'inherit'}
                  sx={{ width: col.width, minWidth: col.minWidth }}
                  sortDirection={col.sortable && sort?.key === col.key ? sort.direction : false}
                >
                  {col.sortable && onSortChange ? (
                    <TableSortLabel
                      active={sort?.key === col.key}
                      direction={sort?.key === col.key ? sort.direction : 'asc'}
                      onClick={() => onSortChange(col.key)}
                    >
                      {col.header}
                    </TableSortLabel>
                  ) : (
                    col.header
                  )}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row) => (
              <TableRow
                key={getRowKey(row)}
                hover={!!onRowClick}
                onClick={onRowClick ? () => onRowClick(row) : undefined}
                sx={{ cursor: onRowClick ? 'pointer' : 'default', '&:last-child td': { border: 0 } }}
              >
                {columns.map((col) => (
                  <TableCell key={col.key} data-col={col.key} align={col.align ?? 'inherit'}>
                    {col.render(row)}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
      {footer ? (
        <Typography variant="caption" sx={{ display: 'block', color: 'text.secondary', mt: 1 }}>
          {footer}
        </Typography>
      ) : null}
    </>
  );
}

export default AdminDataTable;
