import React from 'react';
import TableCell, { TableCellProps } from './TableCell';
import Chevron from '../chevron';
import { Position } from '../common';
import { clsx } from 'clsx';

export interface TableRowType {
  cells?: TableCellProps[];
}

export interface TableRowClickableType extends TableRowType {
  id: number | string; // `id` is mandatory for clickable rows
}

export interface TableRowProps {
  rowData?: TableRowType | TableRowClickableType;
  hasSeparator?: boolean;
  children?: React.ReactNode;
  onRowClick?: (rowData: TableRowType | TableRowClickableType) => void;
}

const TableRow = ({ rowData, hasSeparator = false, children, onRowClick }: TableRowProps) => {
  return (
    <>
      <tr
        className={clsx('np-table-row', { 'np-table-row--clickable': !!onRowClick })}
        data-testid="np-table-row"
        role={onRowClick ? 'button' : undefined}
        tabIndex={0}
        onClick={onRowClick && rowData ? () => onRowClick(rowData) : undefined}
        onKeyDown={({ key }) => {
          if (onRowClick && rowData && key === 'Enter') {
            onRowClick(rowData);
          }
        }}
      >
        {rowData?.cells
          ? rowData?.cells?.map((item, index) => {
              const itemIndex = item.cell?.text ? item.cell?.text.concat(index.toString()) : index;
              return <TableCell key={itemIndex} {...item} />;
            })
          : children}
        {onRowClick && (
          <TableCell className="np-table-cell--action">
            <div aria-hidden="true">
              <Chevron orientation={Position.RIGHT} />
            </div>
          </TableCell>
        )}
      </tr>
      {hasSeparator && (
        <tr
          aria-hidden="true"
          className="np-table-row np-table-row--separator"
          data-testid="np-table-row--separator"
        >
          <td
            className="np-table-cell np-table-cell--cosmetic"
            colSpan={onRowClick ? Number(rowData?.cells?.length) + 1 : rowData?.cells?.length}
            data-testid="np-table-cell--cosmetic"
          >
            <div className="np-table-cell-separator" data-testid="np-table-cell-separator" />
          </td>
        </tr>
      )}
    </>
  );
};

export default TableRow;
