import React from 'react'
import PropTypes from 'prop-types'
import {
  Icon,
  selectSystemProps,
  Typography,
  useThemeTokens,
  getTokensPropType
} from '@telus-uds/components-base'
import styled from 'styled-components'
import { htmlAttrs } from '../utils'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([htmlAttrs])

const getAlignment = (rounded, textAlignToFlex) => {
  if (textAlignToFlex) {
    switch (textAlignToFlex) {
      case 'left':
        return 'flex-start'
      case 'center':
        return 'center'
      default:
        return 'flex-start'
    }
  }
  return rounded ? 'center' : 'flex-start'
}

const verticalAlignToFlex = (verticalAlign) => {
  switch (verticalAlign) {
    case 'top':
      return 'flex-start'
    case 'middle':
      return 'center'
    case 'bottom':
      return 'flex-end'
    default:
      return 'top'
  }
}

const CalloutContainer = styled.div(
  ({ rounded, verticalAlign, textAlignToFlex, background, gap, borderRadius, padding }) => ({
    background,
    display: 'flex',
    gap,
    borderRadius,
    padding,
    justifyContent: getAlignment(rounded, textAlignToFlex),
    alignItems: verticalAlignToFlex(verticalAlign)
  })
)

const Callout = React.forwardRef(
  ({ icon, children, verticalAlign, textAlignToFlex, tokens, variant = {}, ...rest }, ref) => {
    const {
      background,
      gap,
      borderRadius,
      paddingLeft,
      paddingRight,
      paddingTop,
      paddingBottom,
      color
    } = useThemeTokens('Callout', tokens, variant)

    const { rounded = false, size = 'medium' } = variant

    return (
      <CalloutContainer
        size={size}
        rounded={rounded}
        data-testid="callout-container"
        verticalAlign={verticalAlign}
        textAlignToFlex={textAlignToFlex}
        background={background}
        gap={gap}
        borderRadius={borderRadius}
        padding={`${paddingTop}px ${paddingRight}px ${paddingBottom}px ${paddingLeft}px`}
        ref={ref}
        {...selectProps(rest)}
      >
        {icon && <Icon tokens={{ color }} icon={icon} variant={{ rank: 'primary', size }} />}
        <Typography variant={{ size, compact: size === 'small' }} tokens={{ color }}>
          {children}
        </Typography>
      </CalloutContainer>
    )
  }
)

Callout.displayName = 'Callout'

Callout.propTypes = {
  ...selectedSystemPropTypes,
  tokens: getTokensPropType('Callout'),
  /**
   * Icon to display on the left side of the Callout
   */
  icon: PropTypes.elementType,
  /**
   * Children nodes that can be added
   */
  children: PropTypes.node.isRequired,
  /**
   * To change the horizontal alignment of the Callout's text
   */
  textAlignToFlex: PropTypes.oneOf(['center', 'left']),
  /**
   * To change the vertical alignment of the Callout's icon
   */
  verticalAlign: PropTypes.oneOf(['top', 'middle', 'bottom'])
}

export default Callout
