<script setup lang="ts">
import type { TabsContentProps, TabsRootProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { useTextDirection } from '@vueuse/core'
import { ref, watch } from 'vue'
import { cn } from '#utils'
import Icon from '../icon/index.vue'
import { Tabs, TabsContent, TabsList, TabsTrigger } from './tabs'

defineOptions({
  name: 'BuiltInTabs',
})

const props = defineProps<{
  modelValue?: TabsRootProps['modelValue']
  list: {
    icon?: string
    label: string
    value: TabsContentProps['value']
    class?: HTMLAttributes['class']
  }[]
  class?: HTMLAttributes['class']
  listClass?: HTMLAttributes['class']
  contentClass?: HTMLAttributes['class']
}>()

const emits = defineEmits<{
  'update:modelValue': [string | number]
}>()

const dir = useTextDirection({
  observe: true,
})

const activeTab = ref(props.modelValue)

watch(() => props.modelValue, (newValue) => {
  activeTab.value = newValue
})

function handleChange(value: string | number) {
  activeTab.value = value
  emits('update:modelValue', value)
}
</script>

<template>
  <Tabs v-model="activeTab" :dir="dir === 'ltr' ? 'ltr' : 'rtl'" :class="cn('flex flex-col', props.class)" @update:model-value="handleChange">
    <TabsList :class="cn('flex items-center justify-center', props.listClass)">
      <TabsTrigger v-for="item in list" :key="item.value" :value="item.value" :class="cn('w-full', item.class)">
        <div class="flex-center gap-1">
          <Icon v-if="item.icon" :name="item.icon" class="flex-shrink-0" />
          {{ item.label }}
        </div>
      </TabsTrigger>
    </TabsList>
    <TabsContent v-for="item in list" :key="item.value" :value="item.value" :class="props.contentClass">
      <slot :name="item.value" />
    </TabsContent>
  </Tabs>
</template>
