<template>
  <div v-bind="$attrs">
    <div
      role="tablist"
      class="flex justify-center gap-[60px] border-b border-m-primary"
    >
      <button
        v-for="tab in tabs"
        :id="`${componentId}-tab-${tab.key}`"
        :key="tab.key"
        role="tab"
        type="button"
        :aria-selected="activeTab === tab.key"
        :aria-controls="`${componentId}-panel-${tab.key}`"
        :aria-disabled="!!tab.disabled"
        :tabindex="activeTab === tab.key ? 0 : -1"
        :disabled="tab.disabled"
        :class="[
          'relative flex items-center gap-[18px] text-[24px] font-[600] transition-colors',
          activeTab === tab.key
            ? 'cursor-pointer text-m-primary after:content-[\'\'] after:absolute after:-bottom-[3px] after:left-0 after:right-0 after:h-[3px] after:bg-m-primary'
            : tab.disabled
              ? 'cursor-not-allowed text-m-primary/50'
              : 'cursor-pointer text-m-primary/50 hover:text-m-primary/70',
        ]"
        @click="selectTab(tab.key)"
      >
        <IconifyIcon
          v-if="tab.icon"
          :icon="tab.icon"
          :width="tab.iconSize ?? 24"
        />
        {{ tab.label }}
      </button>
    </div>

    <div
      v-for="tab in tabs"
      v-show="activeTab === tab.key"
      :id="`${componentId}-panel-${tab.key}`"
      :key="tab.key"
      role="tabpanel"
      :aria-labelledby="`${componentId}-tab-${tab.key}`"
    >
      <slot :name="tab.key" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, ref, useId} from 'vue'
import {Icon as IconifyIcon} from '@iconify/vue'

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

type Tab = {
  key: string
  label: string
  icon?: string
  iconSize?: string
  disabled?: boolean
}

const props = withDefaults(defineProps<{
  tabs: Tab[]
  modelValue?: string
  id?: string
}>(), {
  modelValue: undefined,
  id: '',
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

const generatedId = useId()
const componentId = computed(() => props.id || `malio-tab-list-${generatedId}`)

const isControlled = computed(() => props.modelValue !== undefined)
const localValue = ref(props.tabs.length > 0 ? props.tabs[0].key : '')

const activeTab = computed(() =>
  isControlled.value ? props.modelValue! : localValue.value,
)

function selectTab(key: string) {
  const tab = props.tabs.find(t => t.key === key)
  if (tab?.disabled) return
  if (!isControlled.value) {
    localValue.value = key
  }
  emit('update:modelValue', key)
}
</script>
