import { makeComponentProps } from '@/composables/component'
import { makeTagProps } from '@/composables/tag'
import { genericComponent, propsFactory } from '@/utils'
import { ExtractPropTypes, PropType, computed } from 'vue'
import Sizes from '@/types/sizes'
import AvatarVariant from '@/types/avatarVariants'
import { UIcon } from '@/components/UIcon/UIcon'

export const makeUAvatarProps = propsFactory(
  {
    size: {
      type: String,
      default: Sizes.sm,
      required: false,
    },
    variant: {
      type: String,
      default: AvatarVariant.default,
      required: false,
    },
    imagePath: {
      type: String,
      default: '',
      required: false,
    },
    avatarIcon: {
      type: [String, null] as PropType<string | null>,
      default: 'imageUser',
      required: false,
    },

    ...makeComponentProps(),
    ...makeTagProps(),
  },
  'UAvatar'
)

export type UAvatarProps = ExtractPropTypes<typeof makeUAvatarProps>

export type UAvatarSlots = {
  default: never
}

export const UAvatar = genericComponent<UAvatarSlots>()({
  name: 'UAvatar',

  props: makeUAvatarProps(),

  emits: {
    click: (e: MouseEvent) => true,
  },

  setup(props, { emit, slots }) {
    const avatarIcon = computed(() => {
      return props.avatarIcon ? props.avatarIcon : ''
    })

    const iconSize = computed(() => {
      const sizeMapping: Record<string, string> = {
        xs: '16',
        sm: '20',
        md: '24',
        lg: '28',
        xl: '32',
      }

      return sizeMapping[props.size] || '32'
    })

    const classes = computed(() => {
      const sizeMapping: Record<string, string> = {
        xxs: 'h-[16px] w-[16px] text-[12px]',
        xs: 'h-[24px] w-[24px] text-[12px]',
        sm: 'h-[32px] w-[32px] text-[14px]',
        md: 'h-[40px] w-[40px] text-[16px]',
        lg: 'h-[48px] w-[48px] text-[18px]',
        xl: 'h-[56px] w-[56px] text-[20px]',
        xxl: 'h-[64px] w-[64px] text-[24px]',
      }

      const sizeClass =
        sizeMapping[props.size] || 'h-[24px] w-[24px] text-[12px]'

      return {
        // eslint-disable-next-line max-len
        'box-border flex items-center justify-center rounded-full overflow-hidden select-none cursor-pointer bg-gray-100 font-medium text-gray-600 active:shadow-xs-btn active:shadow-primary-100':
          true,
        [sizeClass]: true,
      }
    })

    return () => (
      <div class={['avatar', classes.value]} onClick={(e) => emit('click', e)}>
        <img src={props.imagePath} alt="" />
        {avatarIcon.value && !props.imagePath ? (
          <UIcon
            icon={`$${props.avatarIcon}`}
            color="gray-600"
            size={iconSize.value}
          ></UIcon>
        ) : null}
        {props.imagePath === '' && !props.avatarIcon ? slots.default?.() : null}
      </div>
    )
  },
})
