import { TableBody, TableCell } from '@mui/material'
import Spinner from '../../Spinner'
import NoRecordsFound from '../common/NoRecordsFound'
import { StyledTableRow } from '../common/styles'

export const RenderTableBody = ({
  showSerialNumber,
  getTableBodyProps,
  prepareRow,
  rows,
  loading,
  colLength,
  onRowClick,
}) => {
  if (loading)
    return (
      <TableCell colSpan={colLength}>
        <Spinner />
      </TableCell>
    )

  if (!loading && rows?.length < 1)
    return <NoRecordsFound colLength={colLength} />

  return (
    <TableBody {...getTableBodyProps()}>
      {rows?.map((row, index) => {
        prepareRow(row)
        return (
          <StyledTableRow
            onClick={() => {
              if (onRowClick) onRowClick(row)
            }}
            key={index}
            {...row.getRowProps()}
            isSelected={row?.isSelected}
          >
            {showSerialNumber && <TableCell>{index + 1}</TableCell>}
            {row.cells?.map((cell, index) => {
              return (
                <TableCell key={index} {...cell.getCellProps()}>
                  {cell?.render('Cell')}
                </TableCell>
              )
            })}
          </StyledTableRow>
        )
      })}
    </TableBody>
  )
}
