<script setup lang="ts">
import { computed, getCurrentInstance, inject, type Slot } from 'vue'
import { useAttrsWithDefaults } from '../../../composables/useAttrsWithDefaults'
import type { FdsTabsItemProps } from './types'

defineOptions({
  inheritAttrs: false,
})

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

const handleClick = (ev: MouseEvent) => {
  if (props.disabled) {
    ev.preventDefault()
    return
  }
  emit('click', ev)
}

// Try to get route from vue-router if available
const instance = getCurrentInstance()
const route = computed(() => {
  try {
    // Check if vue-router is available via app context
    const router = instance?.appContext.config.globalProperties.$router
    if (router && router.currentRoute) {
      return router.currentRoute.value
    }
  } catch {
    // vue-router not available
  }
  return null
})

const props = withDefaults(defineProps<FdsTabsItemProps>(), {
  to: undefined,
  href: undefined,
  as: undefined,
  active: undefined,
  exact: false,
  disabled: false,
  label: undefined,
  dataTestid: undefined,
})

const { attrs } = useAttrsWithDefaults(props)

const variant = inject<'primary' | 'secondary'>('tabsVariant', 'primary')
const block = inject<boolean>('tabsBlock', false)

// Auto-detect active state from router if to/href is provided
const isActive = computed(() => {
  if (props.active !== undefined) return props.active
  const currentRoute = route.value
  if (!currentRoute) return false

  const currentPath = currentRoute.path

  if (props.exact) {
    // Exact matching
    if (props.to && currentPath === props.to) return true
    if (props.href && currentPath === props.href) return true
  } else {
    // Include matching - check if current path includes to/href
    if (props.to && currentPath.includes(props.to)) return true
    if (props.href && currentPath.includes(props.href)) return true
  }

  return false
})

const componentType = computed(() => {
  if (props.as) return props.as
  if (props.href) return 'a'
  if (props.to) return 'router-link'
  return 'router-link' // Default to router-link
})

const linkAttrs = computed(() => {
  if (componentType.value === 'a') return { href: props.href || props.to }
  if (componentType.value === 'router-link') {
    // If no to/href provided, use current path or empty string
    return { to: props.to || props.href || route.value?.path || '#' }
  }
  return {}
})

const componentAttrs = computed(() => ({
  ...linkAttrs.value,
  ...attrs,
}))

const baseClasses = computed(() => {
  const blockClasses = block ? 'flex flex-1' : ''
  return [
    'text-center',
    blockClasses,
    'flex justify-center w-full cursor-pointer font-bold text-base leading-6 m-0 select-none no-underline whitespace-nowrap',
  ]
})

const variantClasses = computed(() => {
  if (variant === 'primary') {
    return [
      'bg-transparent py-2 px-4 rounded-lg border-2 border-transparent text-inherit',
      isActive.value
        ? 'border-transparent bg-white shadow-md'
        : 'hover:bg-white/59 hover:outline-none active:border-transparent active:bg-white/80',
      'focus-visible:outline-dashed focus-visible:outline-2 focus-visible:outline-blue-500 focus-visible:outline-offset-[-2px]',
    ]
  } else {
    return [
      'text-blue-700 py-1 px-2 rounded-md border-none',
      isActive.value ? 'bg-blue-600 text-white' : 'hover:bg-blue_t-100 active:bg-blue_t-200',
      'focus-visible:outline-dashed focus-visible:outline-2 focus-visible:outline-blue-500',
      'tracking-[0.002em]',
    ]
  }
})

const disabledClasses = computed(() => (props.disabled ? 'cursor-not-allowed pointer-events-none opacity-35' : ''))

const buttonClasses = computed(() => [...baseClasses.value, ...variantClasses.value, disabledClasses.value])

defineSlots<{
  default?: Slot
}>()
</script>

<template>
  <component
    :is="componentType"
    v-bind="componentAttrs"
    :class="buttonClasses"
    :disabled="componentType === 'button' ? props.disabled : undefined"
    :aria-disabled="props.disabled ? 'true' : undefined"
    :aria-current="isActive ? 'page' : undefined"
    :data-testid="dataTestid"
    @click="handleClick"
  >
    {{ label }}
    <slot></slot>
  </component>
</template>
