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

const { t } = useI18n()

const headers = computed(() => [
  { title: 'ID', key: 'id_structure' },
  { title: t('Name'), key: 'nom' },
  { title: 'Pos', key: 'nbcaisses' },
  { title: 'IP', key: 'ip_master', sortable: false },
  { title: t('Phone'), key: 'telephone', sortable: false },
  { title: t('Brand'), key: 'enseigne' },
  { title: t('Country'), key: 'pays' },
  { title: '', key: 'actions', sortable: false },
])

const selectedCountry = ref()
const selectedBrand = ref()
const selectedNbPos = ref()
const searchQuery = ref('')

// Data table options
const { data: storesList } = await useApi<any>(createUrl('/stores'))
const options = ref({ page: 1, itemsPerPage: 10, sortBy: [''], sortDesc: [false] })

const brand = computed(() => {
  const allBrands = storesList.value.map((store: { enseigne: any }) => store.enseigne)
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const uniqueBrands = allBrands.filter((brand: any, index: any, self: string | any[]) => self.indexOf(brand) === index)
  const sortedBrands = uniqueBrands.sort()

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

const country = computed(() => {
  const allCountries = storesList.value.map((store: { pays: any }) => store.pays)
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const uniqueCountries = allCountries.filter((country: any, index: any, self: string | any[]) => self.indexOf(country) === index)
  const sortedCountries = uniqueCountries.sort()

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

const nbPos = computed(() => {
  const allNbPos = storesList.value.map((store: { nbcaisses: number }) => store.nbcaisses)
  const uniqueNbPos = Array.from(new Set(allNbPos)) as number[] // Utilisez une assertion de type
  const sortedNbPos = uniqueNbPos.sort((a, b) => a - b) // Triez les nombres en ordre croissant

  // eslint-disable-next-line @typescript-eslint/no-shadow
  return sortedNbPos.map((nbPos: number) => ({ title: nbPos, value: nbPos }))
})

const filteredStoresList = computed(() => {
  let filtered = storesList.value

  // If a brand is selected, filter the records for this brand
  if (selectedBrand.value)
    filtered = filtered.filter((store: { enseigne: any }) => store.enseigne === selectedBrand.value)

  if (selectedCountry.value)
    filtered = filtered.filter((store: { pays: any }) => store.pays === selectedCountry.value)

  if (selectedNbPos.value)
    filtered = filtered.filter((store: { nbcaisses: any }) => store.nbcaisses === selectedNbPos.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
})

const selectedStore = ref(null)
const isDialogVisible = ref(false)

const openPosList = (store: any) => {
  selectedStore.value = store
  isDialogVisible.value = true
}

interface Store {
  id_structure: number
  caisses: Caisse[]
}
interface Caisse {
  id_caisse: number
  ip: string
}
</script>

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

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

          <!-- 👉 Select Multi POS -->
          <VCol
            cols="12"
            sm="4"
          >
            <AppSelect
              v-model="selectedNbPos"
              :placeholder="$t('Multi POS')"
              :items="nbPos"
              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="$router.push('/apps/ecommerce/product/add')"
          >
            Reload
          </VBtn>
        </div>
      </div>

      <VDivider class="mt-4" />

      <VCol cols="12">
        <!-- 👉 Datatable  -->
        <VDataTable
          :headers="headers"
          :items="filteredStoresList"
          :items-per-page="options.itemsPerPage"
          :page="options.page"
          :options="options"
        >
          <!-- Store details hyperlink -->
          <template #item.nom="{ item }">
            <RouterLink :to="`/store/details?dbHost=${item.ip_master}&storeId=${item.id_structure}`">
              {{ item.nom }}
            </RouterLink>
          </template>

          <!-- Pos count -->
          <template #item.nbcaisses="{ item }">
            <VIcon v-if="item.nbcaisses > 1 && item.nbcaisses <= 9">
              {{ `tabler-square-rounded-number-${item.nbcaisses}` }}
            </VIcon>
            <span v-else-if="item.nbcaisses > 9">{{ item.nbcaisses }}</span>
          </template>

          <!-- Actions -->
          <template #item.actions="{ item }">
            <IconBtn>
              <VIcon icon="tabler-dots-vertical" />
              <VMenu activator="parent">
                <VList>
                  <VListItem
                    value="connect"
                    prepend-icon="tabler-numbers"
                    @click="openPosList(item)"
                  >
                    POS
                  </VListItem>
                </VList>
              </VMenu>
            </IconBtn>
          </template>
        </VDataTable>

        <VDialog
          v-model="isDialogVisible"
          max-width="600"
        >
          <!-- Dialog close btn -->
          <DialogCloseBtn @click="isDialogVisible = !isDialogVisible" />

          <!-- Dialog Content -->
          <VCard title="Connect to invidual POS">
            <VCardText>
              <div v-if="selectedStore && (selectedStore as Store).caisses">
                <div
                  v-for="(caisse, index) in (selectedStore as Store).caisses"
                  :key="index"
                  class="d-flex align-items-center mb-5"
                >
                  <VTextField
                    v-model="caisse.ip"
                    label="IP"
                    class="me-3"
                  />
                  <VBtn
                    :to="`/store/details?dbHost=${caisse.ip}&storeId=${(selectedStore as Store).id_structure}&workstationId=${caisse.id_caisse}`"
                    color="primary"
                  >
                    Pos {{ caisse.id_caisse }}
                  </VBtn>
                </div>
              </div>
            </VCardText>
            <VCardText class="d-flex justify-end flex-wrap gap-3">
              <VBtn
                variant="tonal"
                color="secondary"
                @click="isDialogVisible = false"
              >
                Close
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>
      </VCol>
    </vcard>
  </div>
</template>
