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

const { t } = useI18n()

const headers = computed(() => [
  { title: t('Distributor'), key: 'libelleDis' },
  { title: t('Name'), key: 'nomStructure' },
  { title: t('Chain'), key: 'enseigne' },
  { title: t('Brand'), key: 'marque' },
  { title: t('Season'), key: 'codeSaison' },
  { title: t('R-C-S'), key: 'refRct' },
  { title: t('Item'), key: 'nomProduit' },
  { title: t('Item ID'), key: 'idProduit' },
  { title: t('External Code'), key: 'codeExterne' },
  { title: t('BL ID'), key: 'idBonLivraison' },
  { title: t('BL Date'), key: 'dateBl' },
  { title: t('Expeditor'), key: 'expediteur' },
  { title: t('Notes'), key: 'remarques' },
])

const selectedDistributor = ref()
const selectedStore = ref()
const selectedRefr = ref()

const searchQuery = ref<any>('')

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

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

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

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

const store = computed(() => {
  const allItems = dtListData.value.map(({ nomStructure, idStructure }: { nomStructure: any; idStructure: any }) => ({ nomStructure, idStructure }))

  const uniqueItems = allItems.filter((item: any, index: any, self: any[]) =>
    // eslint-disable-next-line @typescript-eslint/no-shadow
    index === self.findIndex(t => (
      t.nomStructure === item.nomStructure && t.idStructure === item.idStructure
    )),
  )

  const sortedItems = uniqueItems.sort((a: { idStructure: number }, b: { idStructure: number }) => a.idStructure - b.idStructure)

  return sortedItems.map(({ nomStructure }: { nomStructure: any }) => ({ title: nomStructure, value: nomStructure }))
})

const filterRefr = computed(() => {
  const allItems = dtListData.value.map(({ refR }: { refR: any }) => refR)

  const uniqueItems = allItems.filter((refR: any, index: any, self: string | any[]) => self.indexOf(refR) === index)
  const sortedItems = uniqueItems.sort()

  return sortedItems.map((refR: any) => ({ title: refR, value: refR }))
})

const filteredData = computed(() => {
  let filtered = dtListData.value

  // If a distributor is selected, filter the records for this distributor
  if (selectedDistributor.value)
    filtered = filtered.filter(({ libelleDis }: { libelleDis: any }) => libelleDis === selectedDistributor.value)

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

  // If a ref R is selected, filter the records for this ref R
  if (selectedRefr.value)
    filtered = filtered.filter(({ refR }: { refR: any }) => refR === selectedRefr.value)

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

  return filtered
})

const widgetData = computed(() => [
  { title: t('Distributors'), value: distributor.value.length, icon: 'tabler-brand-campaignmonitor' },
  { title: t('Stores'), value: store.value.length, icon: 'tabler-building-store' },
  { title: t('Items'), value: filterRefr.value.length, icon: 'tabler-shirt-sport' },
  { title: t('Errors'), value: dtListData.value.length, icon: 'tabler-exclamation-circle' },
])

const ExcelField = [
  'idDistrib',
  'libelleDis',
  'idStructure',
  'nomStructure',
  'enseigne',
  'marque',
  'codeSaison',
  'refR',
  'refRc',
  'refRct',
  'nomProduit',
  'idProduit',
  'codeExterne',
  'idBonLivraison',
  'dateBl',
  'idExpediteur',
  'expediteur',
  'remarques',
]

const ExcelData = dtListData.value.map((item: { [x: string]: string }) => {
  const orderedItem: { [key: string]: string } = {}

  ExcelField.forEach(field => {
    orderedItem[field] = item[field]
  })

  return orderedItem
})

const exportEXCEL = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  const fileName = `BLBLOQUES_${year}${month}${day}`

  exportFromJSON({
    data: ExcelData,
    fileName,
    exportType: exportFromJSON.types.xls,
  })
}
</script>

<template>
  <VBreadcrumbs
    class="px-0 py-2"
    :items="[
      { title: t('Home'), to: { name: 'root' } },
      { title: t('BL not sent list') },
    ]"
  />
  <div>
    <div>
      <!-- 👉 Statistics Widgets -->
      <VCard class="mb-6">
        <VCardText>
          <VRow>
            <template
              v-for="(data, id) in widgetData"
              :key="id"
            >
              <VCol
                cols="12"
                sm="6"
                md="3"
                class="px-6"
              >
                <div class="d-flex justify-space-between">
                  <div class="d-flex flex-column gap-y-1">
                    <h4
                      class="text-h4 text-high-emphasis"
                      :class="{ 'text-error': id === 3 }"
                    >
                      {{ data.value }}
                    </h4>
                    <div class="text-body-1 text-capitalize">
                      {{ data.title }}
                    </div>
                  </div>

                  <VAvatar
                    color="rgba(var(--v-theme-on-background), var(--v-hover-opacity))"
                    rounded
                    class="text-high-emphasis"
                    size="38"
                  >
                    <VIcon
                      :icon="data.icon"
                      size="26"
                    />
                  </VAvatar>
                </div>
              </VCol>
              <VDivider
                v-if="$vuetify.display.mdAndUp ? id !== widgetData.length - 1
                  : $vuetify.display.smAndUp ? id % 2 === 0
                    : false"
                vertical
                inset
              />
            </template>
          </VRow>
        </VCardText>
      </VCard>

      <VCard
        :title="$t('Filters')"
        class="mb-6"
      >
        <VCardText>
          <VRow>
            <!-- 👉 Select distributor -->
            <VCol
              cols="12"
              sm="4"
            >
              <AppSelect
                v-model="selectedDistributor"
                :placeholder="$t('Distributor')"
                :items="distributor"
                clearable
                clear-icon="tabler-x"
              />
            </VCol>

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

            <!-- 👉 Select Reference R -->
            <VCol
              cols="12"
              sm="4"
            >
              <AppSelect
                v-model="selectedRefr"
                :placeholder="$t('Item')"
                :items="filterRefr"
                clearable
                clear-icon="tabler-x"
              />
            </VCol>
          </VRow>
        </VCardText>
      </VCard>

      <!-- 👉 BL not sent -->
      <VCard
        :title="$t('BL not sent list')"
        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;"
              class="me-3"
            />
          </div>

          <VSpacer />

          <div class="d-flex gap-4 flex-wrap align-center">
            <!-- 👉 Export button -->
            <VBtn
              variant="tonal"
              color="primary"
              prepend-icon="tabler-upload"
              @click="exportEXCEL"
            >
              Export
            </VBtn>
          </div>
        </div>

        <VDivider class="mt-4" />

        <VCol cols="12">
          <!-- 👉 Datatable  -->
          <VDataTable
            class="dt-row-striped"
            :headers="headers"
            :items="filteredData"
            :items-per-page="options.itemsPerPage"
            :page="options.page"
            :options="options"
            density="compact"
          />
        </VCol>
      </Vcard>
    </div>
  </div>
</template>
