<script setup lang="ts">
import { watchEffect } from 'vue'
import { VDataTable } from 'vuetify/labs/VDataTable'

const props = defineProps({
  item: String,
})

const { t } = useI18n()

const route = useRoute('store-details')

// Data table options
const options = ref({ page: 1, itemsPerPage: 10, sortBy: [''], sortDesc: [false] })
const isLoading = ref(false)

const fetchedData = ref<Array<Record<string, unknown>>>([])

const fetchData = async () => {
  isLoading.value = true

  const { data } = await useApi<any>(createUrl(`/items/${props.item}/options?dbHost=${route.query.dbHost}`))

  fetchedData.value = data.value.map((item: any) => ({
    ...item,
    level: `${item.levelCode}:${item.levelValue}`,
  }))

  isLoading.value = false
}

watchEffect(() => {
  if (route.query.dbHost && props.item && !(props.item.trim() === ''))
    fetchData()
})

const headers = computed(() => [
  { title: t('ITEM_ID'), key: 'itemId' },
  { title: 'LEVEL', key: 'level' },
  { title: 'VENDABLE', key: 'itemAvailabilityCode' },
  { title: 'TAXE', key: 'taxGroupId' },
  { title: 'VENDOR', key: 'vendor' },
  { title: 'SEASON', key: 'seasonCode' },
  { title: t('DATE_CREATE'), key: 'createDate' },
  { title: t('USER_CREATE'), key: 'createUserId' },
  { title: t('DATE_UPDATE'), key: 'updateDate' },
  { title: t('USER_UPDATE'), key: 'updateUserId' },
])
</script>

<template>
  <div>
    <VCol>
      <div v-if="isLoading">
        <VProgressCircular
          indeterminate
          color="primary"
        />
      </div>
      <!-- 👉 Datatable  -->
      <VDataTable
        v-else
        :headers="headers"
        :items="fetchedData"
        :items-per-page="options.itemsPerPage"
        :page="options.page"
        :options="options"
        density="compact"
      />
    </VCol>
  </div>
</template>
