import * as stylex from '@stylexjs/stylex';

import type { DataTableProps } from './types';

import { tableStyles } from './styles';

export const Table = <Row,>({
  testId,
  columns,
  rows,
  maxHeight,
  getRowKey,
  renderState,
}: DataTableProps<Row>) => {
  const stateContent = renderState?.({ isEmpty: rows.length === 0 });

  return (
    <div
      data-testid={testId}
      {...stylex.props(tableStyles.container)}
      style={maxHeight ? { maxHeight } : undefined}
    >
      <table {...stylex.props(tableStyles.base)}>
        <thead {...stylex.props(tableStyles.header)}>
          <tr>
            {columns.map((col) => (
              <th
                key={col.key}
                {...stylex.props(tableStyles.headerCell)}
                style={col.align ? { textAlign: col.align } : undefined}
              >
                {col.header}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {stateContent ? (
            <tr data-testid="dataTable-state">
              <td colSpan={columns.length} {...stylex.props(tableStyles.cell)}>
                {stateContent}
              </td>
            </tr>
          ) : (
            rows.map((row, index) => (
              <tr key={getRowKey(row)}>
                {columns.map((col) => (
                  <td
                    key={col.key}
                    {...stylex.props(
                      tableStyles.cell,
                      index % 2 === 1 && tableStyles.alternateCell
                    )}
                    style={col.align ? { textAlign: col.align } : undefined}
                  >
                    {col.renderCell(row, { rowIndex: index })}
                  </td>
                ))}
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );
};
