<template>
  <button
    :id="buttonId"
    :class="mergedButtonClass"
    :disabled="disabled"
    :aria-label="ariaLabel"
    type="button"
    v-bind="attrs"
    @click="onClick"
  >
    <IconifyIcon
      :icon="icon"
      :width="iconSize"
      :height="iconSize"
      data-test="icon"
    />
  </button>
</template>

<script setup lang="ts">
import {computed, useAttrs, useId} from 'vue'
import {Icon as IconifyIcon} from '@iconify/vue'
import {twMerge} from 'tailwind-merge'

defineOptions({name: 'MalioButtonIcon', inheritAttrs: false})

const props = withDefaults(
  defineProps<{
    id?: string
    icon: string
    ariaLabel: string
    disabled?: boolean
    buttonClass?: string
    iconSize?: string | number
    variant?: 'filled' | 'ghost'
  }>(),
  {
    id: '',
    disabled: false,
    buttonClass: '',
    iconSize: 24,
    variant: 'filled',
  },
)

const attrs = useAttrs()
const generatedId = useId()

const buttonId = computed(() => props.id || `malio-button-icon-${generatedId}`)

const isFilled = computed(() => props.variant === 'filled')

const mergedButtonClass = computed(() =>
  twMerge(
    'inline-flex items-center justify-center rounded-md p-1 transition-colors duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-m-primary/50',
    isFilled.value
      ? props.disabled
        ? 'bg-m-btn-disabled text-white cursor-not-allowed'
        : 'bg-m-btn-default hover:bg-m-btn-hover active:bg-m-btn-active text-white cursor-pointer'
      : props.disabled
        ? 'text-m-btn-disabled cursor-not-allowed'
        : 'text-m-btn-default hover:text-m-btn-hover active:text-m-btn-active cursor-pointer',
    props.buttonClass,
  ),
)

const emit = defineEmits<{
  (event: 'click', e: MouseEvent): void
}>()

function onClick(e: MouseEvent) {
  if (!props.disabled) {
    emit('click', e)
  }
}
</script>
