<template>
  <main>
    <span
        ref="btn"
        class="text-ot-green"
        style="cursor: pointer;"
    >
      {{ $t('my_list') }}
    </span>

    <v-menu
        :activator="btn"
        :model-value="showMenu"
        location="start"
        :close-on-content-click="false"
        min-width="500"
        @update:modelValue="onMenuToggled($event)"
    >

      <v-card v-if="collection.totalItems === 0" height="80" class="pa-4">
        <v-card-text class="ma-0 pa-0 header_menu">
          {{ $t('nothing_to_show') }}
        </v-card-text>
      </v-card>

      <v-card v-else>
        <v-card-title class="text-body-2 header-personalized">
          <v-text-field
              v-model="search"
              :label="$t('searchList')"
              :loading="pending"
              density="compact"
              clear-icon="header-personalized"
          />
        </v-card-title>

        <v-card-text class="ma-0 pa-0 mt-n3 header_menu">
          <v-list density="compact" :subheader="true">
            <v-list-item
              v-for="(item, index) in filteredItems"
              :key="index"
              :value="item"
              :href="getListURL(item)"
              exact
            >
              <v-list-item-title>
                {{item.label}} - <strong>{{item.menuKey}}</strong>
              </v-list-item-title>
            </v-list-item>
          </v-list>
        </v-card-text>
      </v-card>

    </v-menu>
  </main>
</template>

<script setup lang="ts">
import PersonalizedList from '~/models/Access/PersonalizedList'
import {useEntityFetch} from "~/composables/data/useEntityFetch";
import {ComputedRef, Ref, ref} from "@vue/reactivity";
import {AnyJson} from "~/types/data";
import ApiResource from "~/models/ApiResource";

const btn: Ref = ref(null)
const showMenu: Ref<boolean> = ref(false)

const onMenuToggled = (event: any) => {
  showMenu.value = event
}

const { fetch, fetchCollection } = useEntityFetch()

const { data: collection, pending } = await fetchCollection(PersonalizedList)

const i18n = useI18n()

const items: ComputedRef<Array<AnyJson>> = computed(() => {
  const lists: Array<ApiResource> = collection.value !== null ? collection.value.items : []

  lists.map(item => {
    item.menuKey = i18n.t(item.menuKey) as string
  })

  return lists
})

const search = ref('');

const filteredItems = computed(() => {
  return items.value.filter( item => {
      return !search.value ||
             item.label.toLowerCase().indexOf(search.value.toLowerCase()) >= 0 ||
             item.menuKey.toLowerCase().indexOf(search.value.toLowerCase()) >= 0
    }
  )
})

const runtimeConfig = useRuntimeConfig()
const homeUrl: string = runtimeConfig.baseUrlAdminLegacy

const getListURL = (list: PersonalizedList) => {
  return `${homeUrl}/${list.entity}/list/${list.id}`
}
</script>

<style lang="scss">
  .header-personalized {
    margin-bottom: 0;
    padding-bottom: 0;
  }
</style>
