import { omitThemingProps, useStyleConfig, vui } from '../core'
import { Svg } from '../svg'
import { cs, filterUndefined } from '../utils'
import { getIconDetails } from './helpers'
import { IconProps } from './icon.types'

/** Displays and Svg element with a given icon. Handles icon names or definition objects. */
export const Icon = vui<'svg', IconProps>((props, ref) => {
  const { className, icon, name = props.icon, rotate, scale, ...rest } = omitThemingProps(props)
  const styles = useStyleConfig('Icon', props)

  const { customIcon, src } = getIconDetails(name)
  const scaledSize = scale ? 16 * scale : undefined

  const aliasedProps = filterUndefined<IconProps>({
    h: scaledSize,
    transform: rotate !== undefined ? `rotate(${rotate}deg)` : undefined,
    w: scaledSize,
  })

  return (
    <Svg
      className={cs('vui-icon', className)}
      clipRule={(customIcon?.pathProps as any)?.clipRule || props?.pathProps?.clipRule || undefined}
      display="inline-flex"
      fillRule={(customIcon?.pathProps as any)?.fillRule || props?.pathProps?.fillRule || undefined}
      flexShrink={0}
      ref={ref}
      src={src}
      {...styles}
      {...customIcon?.svgProps}
      {...aliasedProps}
      {...rest}
    >
      {customIcon?.d.map((d, i) => <path d={d} fill="currentColor" key={i} {...customIcon.pathProps[i]}></path>)}
    </Svg>
  )
})

Icon.displayName = 'Icon'
export default Icon
