import { styled, useStyleConfig, vui } from '../core'
import { cs } from '../utils'
import { useTableContext } from './context'
import { TheadProps } from './table.types'
import Th from './th'
import Tr from './tr'

/*@formatter:off*/
const TheadBase = styled.theadBox`
  tr th,
  tr td {
    border-bottom: 1px solid sandstone.main;
  }
`
/*@formatter:on*/

/** Displays Table head with support for columns and sticky. */
export const Thead = vui<'thead', TheadProps>((props, ref) => {
  const { children, className, ...rest } = props
  const { columns, stickyHeader } = useTableContext() ?? {}
  const styles = useStyleConfig('Table', useTableContext())

  const stickyProps = stickyHeader
    ? {
        bg: 'white',
        position: 'sticky',
        top: 0,
        zIndex: 3,
      }
    : {}

  return (
    <TheadBase className={cs('vui-thead', className)} ref={ref} {...stickyProps} {...styles.thead} {...rest}>
      {children ?? <Tr>{columns?.map(column => <Th key={column.field} role="columnheader" {...column} />)}</Tr>}
    </TheadBase>
  )
})

Thead.displayName = 'Thead'

export default Thead
