import Box from '../box'
import { styled, useStyleConfig, vui } from '../core'
import { cs, MouseEvent, useCallbackRef } from '../utils'
import { useTableContext } from './context'
import { ThProps } from './table.types'
import TableSortIcon from './tableSortIcon'

export const ThBase = styled.thBox`
  font-weight: demi;
  text-align: left;
  transition-duration: fast;
`

/** Displays Table heading with support for sort. */
export const Th = vui<'th', ThProps>((props, ref) => {
  const {
    children,
    className,
    disabled,
    field,
    isInteractive: isInteractiveProp,
    isSortable,
    onClick: onClickProp,
    title,
    ...rest
  } = props
  const { onSortChange, sort } = useTableContext() ?? {}
  const styles = useStyleConfig('Table', useTableContext())

  const onClick = isSortable
    ? useCallbackRef((e: MouseEvent<HTMLTableCellElement>) => {
        onClickProp?.(e)
        field && onSortChange(field)
      })
    : onClickProp

  const isActive = !disabled && sort?.key === field
  const sortOrder = isActive ? sort.order : undefined
  const isInteractive = isInteractiveProp ?? onClick !== undefined

  const activeProps = isActive ? { bg: 'skyBlue.active' } : {}
  const disabledProps = disabled ? { bg: 'disabled.bg', color: 'disabled.color', cursor: 'not-allowed' } : {}
  const hoverBg = isSortable ? 'skyBlue.hover' : undefined

  const interactiveProps =
    !disabled && isInteractive
      ? {
          cursor: 'pointer',
          onClick,
          tabIndex: 0,
          userSelect: 'none',
        }
      : {}

  return (
    <ThBase
      className={cs('vui-th', className)}
      data-active={isActive}
      data-disabled={disabled}
      hoverBg={hoverBg}
      px={2}
      ref={ref}
      {...styles.th}
      {...activeProps}
      {...disabledProps}
      {...interactiveProps}
      {...rest}
    >
      {children ?? (
        <Box centerV display="inline-flex">
          {title}
          {isSortable && <TableSortIcon ml={1} my={0.5} order={sortOrder} />}
        </Box>
      )}
    </ThBase>
  )
})

Th.displayName = 'Th'

export default Th
