import Box from '../box'
import { useStyleConfig, vui } from '../core'
import Icon from '../icon'
import P from '../p'
import { cs, isJsx } from '../utils'
import { inputColors } from './consts'
import { useInputContext } from './context'
import type { HelpTextProps } from './input.types'

/** Displaying help text below the input. */
export const HelpText = vui<'div', HelpTextProps>((props, ref) => {
  const { className, children, isError, ...rest } = props
  const inputProps = useInputContext()
  const mergedProps = { ...inputProps, ...props }
  const styles = useStyleConfig('Input', mergedProps)

  const color = isError ? inputColors.error : inputColors.helpText

  if (isJsx(children)) {
    return (
      <Box
        alignItems="flex-start"
        className={cs('vui-inputHelpText', className)}
        color={color}
        display="flex"
        pt={0.5}
        ref={ref}
        {...styles.helpText}
        {...rest}
      >
        {isError && <Icon mr={1} mt="3px" name="uiExclamationTriangle" pathFill={inputColors.error} size="sm" />}
        {children}
      </Box>
    )
  }
  // Fallback for string children
  return (
    <P
      alignItems="flex-start"
      className={cs('vui-inputHelpText', className)}
      color={color}
      display="flex"
      fontSize={isError ? 'md' : 'sm'}
      pt={0.5}
      ref={ref}
      {...styles.helpText}
      {...rest}
    >
      {isError && <Icon mr={1} mt="3px" name="uiExclamationTriangle" pathFill={inputColors.error} size="sm" />}
      {children}
    </P>
  )
})

HelpText.displayName = 'HelpText'
export default HelpText
