<!--
Copyright (c) 2026 Sidero Labs, Inc.

Use of this software is governed by the Business Source License
included in the LICENSE file.
-->
<script setup lang="ts">
import {
  type AnchorHTMLAttributes,
  type ButtonHTMLAttributes,
  computed,
  type HTMLAttributes,
  useAttrs,
} from 'vue'
import type { RouterLinkProps } from 'vue-router'
import { RouterLink } from 'vue-router'

import type { IconType } from '@/components/Icon/TIcon.vue'
import TIcon from '@/components/Icon/TIcon.vue'
import { cn } from '@/methods/utils'

interface Props {
  icon?: IconType
  danger?: boolean
  iconClasses?: unknown
  class?: HTMLAttributes['class']
}

interface ButtonProps extends /* @vue-ignore */ ButtonHTMLAttributes {
  is?: 'button'
  href?: never
  to?: never
}

interface AnchorProps extends /* @vue-ignore */ AnchorHTMLAttributes {
  // eslint-disable-next-line vue/no-required-prop-with-default
  is: 'a'
  href: string
  to?: never
  disabled?: boolean
}

interface RLink extends RouterLinkProps {
  // eslint-disable-next-line vue/no-required-prop-with-default
  is: 'router-link'
  href?: never
  to: RouterLinkProps['to']
  disabled?: boolean
}

const {
  is = 'button',
  to,
  href,
  disabled,
  class: className,
} = defineProps<Props & (ButtonProps | AnchorProps | RLink)>()
const attrs = useAttrs()

const dynamicProps = computed(() => {
  // <a> does not support disabled, so we force <button> in that case
  if (!disabled) {
    if (to) return { to }
    if (href) return { href }
  }

  return { type: (attrs.type as string) || 'button', disabled }
})
</script>

<template>
  <component
    :is="disabled ? 'button' : is === 'router-link' ? RouterLink : is"
    v-bind="dynamicProps"
    :class="
      cn(
        'h-6 w-6 rounded align-top text-naturals-n11 transition-all duration-100 hover:bg-naturals-n7 hover:text-naturals-n13 disabled:pointer-events-none disabled:cursor-not-allowed disabled:text-naturals-n7',
        { 'text-red-r1': danger },
        className,
      )
    "
  >
    <slot>
      <TIcon class="h-full w-full cursor-pointer p-1" :class="iconClasses" :icon="icon" />
    </slot>
  </component>
</template>
