<script setup lang="ts">
import { endOfDay, format } from 'date-fns'
import exportFromJSON from 'export-from-json'
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: '', key: 'data-table-expand' },
  { title: t('WSK'), key: 'wkstnId' },
  { title: t('Level'), key: 'logLevel' },
  { title: t('Category'), key: 'loggerCategory' },
  { title: t('Thread'), key: 'threadName' },
  { title: t('Date'), key: 'createDate' },
  { title: t('Business Date'), key: 'businessDate' },
  { title: t('User'), key: 'createUserId' },
])

const selectedWkStn = ref(null)
const selectedLogLevel = ref(null)
const selectedCategory = ref(null)
const selectedDate = ref(null)
const searchQuery = ref('')

interface Props {
  storeData: StoreData
}

const isSnackbarExport = ref(false)

// Data table options
// TODO SortBy ne marche pas
const options = ref({ page: 1, itemsPerPage: 10, sortBy: ['createDate'], sortDesc: [true] })
const isLoading = ref(false)

const dtListData = ref([])

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

  let logDate
  if (selectedDate.value)
    logDate = format(new Date(selectedDate.value), 'yyyyMMdd')
  else
    logDate = format(endOfDay(new Date()), 'yyyyMMdd')

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

  if (response.data.value)
    dtListData.value = response.data.value
  else
    dtListData.value = []

  isLoading.value = false
}

const wkstn = computed(() => {
  const allWkstns = dtListData.value.map((list: { wkstnId: any }) => list.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()

  return sortedWkstns.map((list: any) => ({ title: list, value: list }))
})

const level = computed(() => {
  const allLogLevels = dtListData.value.map((list: { logLevel: any }) => list.logLevel)
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const uniqueLogLevels = allLogLevels.filter((level: any, index: any, self: string | any[]) => self.indexOf(level) === index)
  const sortedLogLevels = uniqueLogLevels.sort()

  return sortedLogLevels.map((list: any) => ({ title: list, value: list }))
})

const category = computed(() => {
  const allCategories = dtListData.value.map((list: { loggerCategory: any }) => list.loggerCategory)
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const uniqueCategories = allCategories.filter((category: any, index: any, self: string | any[]) => self.indexOf(category) === index)
  const sortedCategories = uniqueCategories.sort()

  return sortedCategories.map((list: any) => ({ title: list, value: list }))
})

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

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

  // If a loglevel is selected, filter the records for this Loglevel
  if (selectedLogLevel.value !== undefined && selectedLogLevel.value !== null)
    filtered = filtered.filter((list: { logLevel: any }) => list.logLevel === selectedLogLevel.value)

  // If a loggerCategory is selected, filter the records for this loggerCategory
  if (selectedCategory.value !== undefined && selectedCategory.value !== null)
    filtered = filtered.filter((list: { loggerCategory: any }) => list.loggerCategory === selectedCategory.value)

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

  return filtered
})

const ExcelField = [
  'wkstnId',
  'logLevel',
  'threadName',
  'logMessage',
  'loggerCategory',
  'createDate',
  'createUserId',
]

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

    ExcelField.forEach(field => {
      if (field === 'createDate') {
        const date = new Date(item[field])

        orderedItem[field] = format(date, 'dd/MM/yyyy HH:mm:ss')
      }
      else {
        orderedItem[field] = item[field]
      }
    })

    return orderedItem
  })
})

const exportEXCEL = () => {
  const fileName = `LOGS_${props.storeData.store.id_structure}-${format(new Date(), 'yyyyMMdd')}`

  if (ExcelData.value.length > 0) {
    exportFromJSON({
      data: ExcelData.value,
      fileName,
      exportType: exportFromJSON.types.xls,
    })
  }
  else {
    isSnackbarExport.value = true
  }
}
</script>

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

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

          <!-- 👉 Select logger category -->
          <VCol
            cols="12"
            sm="4"
          >
            <AppSelect
              v-model="selectedCategory"
              :placeholder="$t('loggerCategory')"
              :items="category"
              clearable
              clear-icon="tabler-x"
            />
          </VCol>
        </VRow>
        <VRow>
          <!-- 👉 Date log  -->
          <VCol sm="4">
            <AppDateTimePicker
              v-model="selectedDate"
              label=""
              :placeholder="$t('Select date')"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>
    <!-- 👉 datatable, search & export & reload -->
    <VCard
      :title="$t('Logs 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-1 flex-wrap aalign-center">
          <!-- 👉 Export button -->
          <VBtn
            variant="tonal"
            color="primary"
            prepend-icon="tabler-upload"
            @click="exportEXCEL"
          >
            Export
          </VBtn>
        </div>
        <!-- 👉 Reload  -->
        <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
          class="dt-row-striped"
          :headers="headers"
          :items="filteredLogList"
          :items-per-page="options.itemsPerPage"
          :page="options.page"
          :options="options"
          density="compact"
          expand-on-click
        >
          <!-- format date log -->
          <template #item.createDate="{ item }">
            {{ format(new Date(item.createDate), 'dd/MM/yyyy HH:mm:ss') }}
          </template>

          <!-- format business date -->
          <template #item.businessDate="{ item }">
            {{ format(new Date(item.businessDate), 'dd/MM/yyyy') }}
          </template>

          <!-- Expanded Row Data -->
          <template #expanded-row="slotProps">
            <tr class="v-data-table__tr">
              <td :colspan="headers.length">
                <p class="my-1">
                  {{ slotProps.item.logMessage }}
                </p>
              </td>
            </tr>
          </template>
        </VDataTable>
      </VCol>
    </VCard>
  </div>
  <!-- Snackbar Export -->
  <VSnackbar
    v-model="isSnackbarExport"
    location="center"
  >
    {{ $t('ExcelData is empty, cannot export') }}

    <template #actions>
      <VBtn
        color="error"
        @click="isSnackbarExport = false"
      >
        {{ $t("Close") }}
      </VBtn>
    </template>
  </VSnackbar>
</template>
