import React from 'react'

import { styled, useStyleConfig, vui } from '../core'
import { cs } from '../utils'
import { useTableContext } from './context'
import { TbodyProps } from './table.types'
import Td from './td'
import Tr from './tr'

export const TbodyBase = styled.tbodyBox`
  tr {
    :hover td {
      background-color: skyBlue.hover;
    }

    &[data-selected='true']:hover td {
      background-color: skyBlue.hover;
    }

    &[data-selected='true'] td {
      border-bottom-color: sandstone.main;
    }

    &[data-variant='striped'][data-selected='false']:nth-of-type(odd):not(:hover) td {
      background-color: sandstone.95;
    }

    &[data-variant='basic']:hover td {
      background-color: transparent;
    }
  }
`

/** Displays Table body with built-in support for rows. */
export const Tbody = vui<'tbody', TbodyProps>((props, ref) => {
  const { children, className, ...rest } = props
  const { columns, rows } = useTableContext() ?? {}
  const styles = useStyleConfig('Table', useTableContext())

  return (
    <TbodyBase className={cs('vui-tbody', className)} ref={ref} {...styles.tbody} {...rest}>
      {children ??
        rows?.map((row, index) => (
          <Tr key={index}>{columns?.map(column => <Td key={column.field}>{row[column.field]}</Td>)}</Tr>
        ))}
    </TbodyBase>
  )
})

Tbody.displayName = 'Tbody'

export default Tbody
