import Box from '../box'
import { styled, useStyleConfig, vui } from '../core'
import Icon from '../icon'
import P from '../p'
import { cs, isArray } from '../utils'
import { DefinitionItem, DefinitionProps } from './definition.types'

export const DefinitionItemKey = styled.dtBox``
export const DefinitionItemValue = styled.ddBox``

export const DefinitionContent = vui<'dl', DefinitionProps>((props, ref) => {
  const { iconLeft, iconRight, isLabelBold, isValueBold, items, orientation } = props as DefinitionProps

  const styles = useStyleConfig('Definition', props)

  return (
    <>
      {isArray<DefinitionItem>(items)
        ? items.map(({ key, value, ...props }, index) => (
            <Box className="vui-definitionItemWrapper" key={index} ref={ref}>
              <DefinitionItemKey fontWeight={isLabelBold ? 'demi' : 'default'} {...styles.dt}>
                {props.keyHasIcon && iconLeft && (
                  <Icon className={cs('vui-definitionIcon')} name={iconLeft} {...styles.icon} />
                )}
                {key}
                {props.keyHasIcon && iconRight && (
                  <Icon className={cs('vui-definitionIcon')} name={iconRight} {...styles.icon} />
                )}
              </DefinitionItemKey>
              {isArray(value) ? (
                <DefinitionItemValue
                  display="block"
                  fontWeight={isValueBold ? 'demi' : 'default'}
                  {...styles.dd}
                  key={index}
                >
                  {orientation === 'horizontal'
                    ? value.join(', ')
                    : value.map((value, index) => (
                        <P display="flex" key={index + value}>
                          {props.valueHasIcon && iconLeft && (
                            <Icon className={cs('vui-definitionIcon')} name={iconLeft} {...styles.icon} />
                          )}
                          {value}
                          {props.valueHasIcon && iconRight && (
                            <Icon className={cs('vui-definitionIcon')} name={iconRight} {...styles.icon} />
                          )}
                        </P>
                      ))}
                  {}
                </DefinitionItemValue>
              ) : (
                <DefinitionItemValue fontWeight={isValueBold ? 'demi' : 'default'} {...styles.dd}>
                  {props.valueHasIcon && iconLeft && (
                    <Icon className={cs('vui-definitionIcon')} name={iconLeft} {...styles.icon} />
                  )}
                  {value}
                  {props.valueHasIcon && iconRight && (
                    <Icon className={cs('vui-definitionIcon')} name={iconRight} {...styles.icon} />
                  )}
                </DefinitionItemValue>
              )}
            </Box>
          ))
        : items}
    </>
  )
})

DefinitionContent.displayName = 'DefinitionContent'

export default DefinitionContent
