import { highlightedOnActive, highlightedOnHover } from '@/analyst/utilities'
import type { NonIdealStateProps } from '@blueprintjs/core'
import { NonIdealState, Spinner } from '@blueprintjs/core'
import { cx } from '@emotion/css'
import { ellipsized } from '@inject/shared/css/textOverflow'
import { clickable, preWrappedOnHover, tableCell } from './classes'
import type { Column, Row } from './typing'

type BodyProps<T> = {
  columns: Column<T>[]
  loading?: boolean
  rows: Row<T>[]
  noDataStateProps?: NonIdealStateProps
}

const Body = <T,>({
  columns,
  rows,
  loading,
  noDataStateProps,
}: BodyProps<T>) => {
  if (loading || rows?.length === 0) {
    return (
      <tbody>
        <tr>
          <td colSpan={columns.length} className={tableCell}>
            {loading ? (
              <Spinner />
            ) : (
              <NonIdealState
                title='No data'
                icon='low-voltage-pole'
                description='There is no data to display'
                {...noDataStateProps}
              />
            )}
          </td>
        </tr>
      </tbody>
    )
  }

  return (
    <tbody>
      {rows.map(row => (
        <tr
          key={row.id}
          className={cx(highlightedOnHover, row.className, {
            [clickable]: row.onClick !== undefined,
            [highlightedOnActive]: row.onClick !== undefined,
          })}
          style={row.style}
          onClick={row.onClick}
        >
          {columns.map(column => (
            <td
              key={column.id}
              className={cx(
                tableCell,
                ellipsized,
                preWrappedOnHover,
                column.className,
                column.valueClassName?.(row.value)
              )}
              style={{
                ...column.style,
                ...column.valueStyle?.(row.value),
              }}
            >
              {column.renderValue(row.value)}
            </td>
          ))}
        </tr>
      ))}
    </tbody>
  )
}
export default Body
