<script setup lang="ts">
import { VDataTable } from 'vuetify/labs/VDataTable'
import type { StoreData } from '@/models/storeData'

const props = defineProps<Props>()
const { t } = useI18n()

const route = useRoute('store-details')

const headers = computed(() => [
  { title: 'WSK', key: 'wkstnId' },
  { title: t('Name'), key: 'signatureId' },
  { title: t('Mode'), key: 'signatureMode' },
  { title: t('SignatureString'), key: 'signatureString' },
  { title: t('SignatureSource'), key: 'signatureSource' },
  { title: t('DATE_CREATE'), key: 'createDate' },
  { title: t('USER_CREATE'), key: 'createUserId' },
  { title: t('DATE_UPDATE'), key: 'updateDate' },
  { title: t('USER_UPDATE'), key: 'updateUserId' },
])

const selectedWkStn = ref()
const selectedSignatureMode = ref()
const searchQuery = ref('')

interface Props {
  storeData: StoreData
}

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

const data = ref([]) // Initialisez data comme un tableau vide

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

  const response = await useApi<any>(createUrl(`/stores/${props.storeData.store.id_structure}/signature?dbHost=${route.query.dbHost}`))

  data.value = response.data.value

  isLoading.value = false
}

const wkstn = computed(() => {
  const allWkstns = data.value.map((store: { wkstnId: any }) => store.wkstnId)
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const uniqueWkstns = allWkstns.filter((wkstn: any, index: any, self: string | any[]) => self.indexOf(wkstn) === index)
  const sortedWkstns = uniqueWkstns.sort()

  // eslint-disable-next-line @typescript-eslint/no-shadow
  return sortedWkstns.map((wkstn: any) => ({ title: wkstn, value: wkstn }))
})

const signmode = computed(() => {
  const allSignModes = data.value.map((store: { signMode: any }) => store.signMode)

  const uniqueSignMoeds = allSignModes.filter((signmod: any, index: any, self: string | any[]) => self.indexOf(signmod) === index)
  const sortedSignMoeds = uniqueSignMoeds.sort()

  return sortedSignMoeds.map((signmod: any) => ({ title: signmod, value: signmod }))
})

const filteredSigantureList = computed(() => {
  let filtered = data.value

  // If a workstation is selected, filter the records for this number
  if (selectedWkStn.value !== undefined && selectedWkStn.value !== null)
    filtered = filtered.filter((store: { wkstnId: any }) => store.wkstnId === selectedWkStn.value)

  // If a signature mode is selected, filter the records for this mode
  if (selectedSignatureMode.value !== undefined && selectedSignatureMode.value !== null)
    filtered = filtered.filter((store: { signMode: any }) => store.signMode === selectedSignatureMode.value)

  // If a search query is provided, filter the records for this query
  if (searchQuery.value) {
    filtered = filtered.filter((store: { [s: string]: unknown } | ArrayLike<unknown>) =>
      Object.values(store).some(value =>
        String(value).toLowerCase().includes(searchQuery.value.toLowerCase()),
      ),
    )
  }

  return filtered
})
</script>

<template>
  <div>
    <!-- 👉 stores -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <!-- 👉 Select country -->
          <VCol
            cols="12"
            sm="4"
          >
            <AppSelect
              v-model="selectedWkStn"
              :placeholder="$t('WorkStation')"
              :items="wkstn"
              clearable
              clear-icon="tabler-x"
            />
          </VCol>

          <!-- 👉 Select Brand -->
          <VCol
            cols="12"
            sm="4"
          >
            <AppSelect
              v-model="selectedSignatureMode"
              :placeholder="$t('Mode')"
              :items="signmode"
              clearable
              clear-icon="tabler-x"
            />
          </VCol>
        </VRow>
      </VCardText>

      <VDivider class="my-4" />

      <div class="d-flex flex-wrap gap-4 mx-5">
        <div class="d-flex align-center">
          <!-- 👉 Search  -->
          <AppTextField
            v-model="searchQuery"
            :placeholder="$t('Search')"
            density="compact"
            style="inline-size: 200px;"
            class="me-3"
          />
        </div>
        <VSpacer />
        <div class="d-flex gap-4 flex-wrap align-center">
          <VBtn
            color="primary"
            prepend-icon="tabler-reload"
            @click="fetchData"
          >
            {{ $t('Reload') }}
          </VBtn>
        </div>
      </div>

      <VDivider class="mt-4" />

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