<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: 'sequenceId' },
  { title: t('Mode'), key: 'sequenceMode' },
  { title: t('Value'), key: 'sequenceNbr' },
  { 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 selectedSequenceMode = 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}/sequence?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 seqmode = computed(() => {
  const allSeqModes = data.value.map((store: { sequenceMode: any }) => store.sequenceMode)

  const uniqueSeqModes = allSeqModes.filter((seqmod: any, index: any, self: string | any[]) => self.indexOf(seqmod) === index)
  const sortedSeqModes = uniqueSeqModes.sort()

  return sortedSeqModes.map((seqmod: any) => ({ title: seqmod, value: seqmod }))
})

const filteredSequenceList = 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 sequence mode is selected, filter the records for this mode
  if (selectedSequenceMode.value !== undefined && selectedSequenceMode.value !== null)
    filtered = filtered.filter((store: { sequenceMode: any }) => store.sequenceMode === selectedSequenceMode.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="selectedSequenceMode"
              :placeholder="$t('Mode')"
              :items="seqmode"
              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="filteredSequenceList"
          :items-per-page="options.itemsPerPage"
          :page="options.page"
          :options="options"
          density="compact"
        />
      </VCol>
    </VCard>
  </div>
</template>
