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

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;
}

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;
}

/**
 * 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.
 * @component AdminDataTable
 */
function AdminDataTable<T>({ columns, rows, getRowKey, onRowClick, dense = true, ariaLabel }: AdminDataTableProps<T>) {
  return (
    <TableContainer component={Paper} elevation={0} sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 2, overflowX: 'auto' }}>
      <Table 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 }}>
                {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>
  );
}

export default AdminDataTable;
