import { useEffect, useState } from 'react'

import Button from '../button'
import { styled, useStyleConfig, vui } from '../core'
import { cs } from '../utils'
import { useTableContext } from './context'
import { TrProps } from './table.types'
import Td from './td'

const trClassName = 'vui-tr'
const buttonClassName = (isExpanded?: boolean) => `falAngle${isExpanded ? 'Down' : 'Right'}`

export const TrBase = styled.trBox`
  position: relative;
  transition-duration: fast;
`

/** Displays Table row that can contain heading or data cells. */
export const Tr = vui<'tr', TrProps>((props, ref) => {
  const { className, isExpanded: isExpandedProp, isSelected, nested, onCollapsed, onExpanded, ...rest } = props
  const { variant } = useTableContext() ?? {}
  const styles = useStyleConfig('Table', useTableContext())
  const [isExpanded, setIsExpanded] = useState(isExpandedProp)

  useEffect(() => {
    setIsExpanded(isExpandedProp)
  }, [isExpandedProp])

  const onToggle = () => {
    if (isExpanded) {
      setIsExpanded(false)
      onCollapsed?.()
    } else {
      setIsExpanded(true)
      onExpanded?.()
    }
  }

  const selectedProps = isSelected ? { bg: 'skyBlue.selected' } : {}

  rest.children = (
    <>
      {nested !== undefined && (
        <Td maxW={16} px={0} textAlign="center">
          {nested ? <Button icon={buttonClassName(isExpanded)} onClick={onToggle} variant="subtleBlue" /> : null}
        </Td>
      )}
      {rest.children}
    </>
  )

  return (
    <>
      <TrBase
        className={cs(trClassName, `${trClassName}-${isExpanded ? 'expanded' : 'collapsed'}`, className)}
        data-selected={Boolean(isSelected)}
        data-variant={variant}
        ref={ref}
        {...styles.tr}
        {...selectedProps}
        {...rest}
      />
      {isExpanded && nested}
    </>
  )
})

Tr.displayName = 'Tr'
export default Tr
