import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { useTableContext } from './Table'

const StyledTR = styled.tr`
  &:hover {
    background-color: ${({ $tokens }) => $tokens?.rowHoverBackgroundColor} !important;
  }
  border-style: ${({ $tokens }) =>
    $tokens?.rowBorderWidth || $tokens?.rowBorderTopWidth ? 'solid' : 'none'};
  border-color: ${({ $tokens }) => $tokens?.rowBorderColor};
  border-width: ${({ $tokens }) => `${$tokens?.rowBorderWidth}` || 0}px;
  border-top-width: ${({ $tokens }) =>
    `${$tokens?.rowBorderTopWidth}` || $tokens?.rowBorderWidth}px;
`

export const TableRow = React.forwardRef(({ children, tokens: rowTokens }, ref) => {
  const { themeTokens } = useTableContext()
  const mergedTokens = { ...themeTokens, ...rowTokens }

  return (
    <StyledTR ref={ref} $tokens={mergedTokens}>
      {React.Children.map(children, (child, index) =>
        React.cloneElement(child, { isFirstInRow: index === 0 })
      )}
    </StyledTR>
  )
})

TableRow.displayName = 'TableRow'

TableRow.propTypes = {
  tokens: PropTypes.shape({
    borderColor: PropTypes.string,
    topBorderWidth: PropTypes.string,
    bottomBorderWidth: PropTypes.string,
    leftBorderWidth: PropTypes.string,
    rightBorderWidth: PropTypes.string,
    rowHoverBackgroundColor: PropTypes.string
  }),
  children: PropTypes.node
}
