<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { VDataTable } from 'vuetify/labs/VDataTable'
import { useDataTableStore } from '@/stores/datatable.store'

const { t } = useI18n()
const router = useRouter()
const route = useRoute()

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

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

// for reload process
const storesList = ref<any>('')
const isLoading = ref(false)

const searchQuery = ref<any>('')

// Data table options
const { data: dtListData } = await useApi<any>(createUrl('/stores'))

storesList.value = dtListData.value

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

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

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

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

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

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

const filteredData = 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 a country is selected, filter the records for this country
  if (selectedCountry.value)
    filtered = filtered.filter((store: { pays: any }) => store.pays === selectedCountry.value)

  // If a number of POS is selected, filter the records for this number
  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
}

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

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { data, error } = await useApi<any>(createUrl('/stores/reload'))

  if (!isEmpty(error.value))
    console.error('Error loading store data:', error.value)

  // Reload the store data
  const { data: storeData, error: storeError } = await useApi<any>(createUrl('/stores'))
  if (!isEmpty(storeError.value))
    console.error('Error loading store data:', storeError.value)
  else
    storesList.value = storeData.value

  isLoading.value = false
}

// pinia store for datatable filters & options
const stStoreList = useDataTableStore()

const saveDtFilters = () => {
  stStoreList.setFilters('selectedCountry', selectedCountry.value)
  stStoreList.setFilters('selectedBrand', selectedBrand.value)
  stStoreList.setFilters('selectedNbPos', selectedNbPos.value)
  stStoreList.searchText = searchQuery.value
}

const restoreDtFilters = () => {
  if (stStoreList.filters.selectedCountry)
    selectedCountry.value = stStoreList.filters.selectedCountry

  if (stStoreList.filters.selectedBrand)
    selectedBrand.value = stStoreList.filters.selectedBrand

  if (stStoreList.filters.selectedNbPos)
    selectedNbPos.value = stStoreList.filters.selectedNbPos

  if (stStoreList.searchText)
    searchQuery.value = stStoreList.searchText
}

const navigateToStoreDetails = (item: { ip_master: string; id_structure: number }) => {
  // Save datatable filters state
  saveDtFilters()

  // go to store details
  router.push(`/store/details?dbHost=${item.ip_master}&storeId=${item.id_structure}`)
}

onMounted(() => {
  // Restore datatable filters state on page load
  restoreDtFilters()
})

watch(route, (to, from) => {
  if (from && from.path !== '/store/details')
    stStoreList.clearState()
}, { immediate: true })
</script>

<template>
  <VBreadcrumbs
    class="px-0 py-2"
    :items="[
      { title: t('Home'), to: { name: 'root' } },
      { title: t('List of stores') },
    ]"
  />
  <div>
    <!-- 👉 filters -->
    <VCard
      :title="$t('Filters')"
      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('Sign')"
              :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>
    </VCard>
    <!-- 👉 datatable, search & export & reload -->
    <VCard
      :title="$t('List of stores')"
      class="mb-6"
    >
      <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;"
            type="text"
            class="me-3"
          />
        </div>
        <VSpacer />
        <div class="d-flex gap-4 flex-wrap align-center">
          <VBtn
            color="primary"
            prepend-icon="tabler-reload"
            @click="reloadStores"
          >
            {{ t("Reload") }}
          </VBtn>
        </div>
      </div>

      <VDivider class="mt-4" />

      <VCol cols="12">
        <div v-if="isLoading">
          <VProgressCircular
            indeterminate
            color="primary"
          />
        </div>
        <!-- 👉 Datatable  https://vuetifyjs.com/en/api/v-data-table/#props -->
        <VDataTable
          v-else
          :headers="headers"
          :items="filteredData"
          :items-per-page="stStoreList.itemsPerPage"
          :page="stStoreList.currentPage"
          :sort-by="stStoreList.getSortBy()"
          density="compact"
          @update:sort-by="sortBy => { stStoreList.setSortBy(sortBy[0]?.key) ; stStoreList.setSortOrder(sortBy[0]?.order) }"
          @update:items-per-page="itemsPerPage => { stStoreList.setItemsPerPage(itemsPerPage) }"
          @update:page="page => { stStoreList.setCurrentPage(page) }"
        >
          <!-- Store details hyperlink -->
          <template #item.nom="{ item }">
            <a
              href="#"
              class="router-link"
              @click.prevent="navigateToStoreDetails(item)"
            >
              {{ item.nom }}
            </a>
          </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>
        <!-- 👉 Dialog page for line actions  -->
        <VDialog
          v-model="isDialogVisible"
          max-width="600"
        >
          <!-- Dialog close btn -->
          <DialogCloseBtn @click="isDialogVisible = !isDialogVisible" />

          <!-- Dialog Content -->
          <VCard :title="t('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"
              >
                {{ $t("Close") }}
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>
      </VCol>
    </VCard>
  </div>
</template>
