<template>
  <main>
    <a ref="btn" id="activator">
      {{ $t('my_list') }}
    </a>

    <v-menu
        :activator="btn"
        offset="10"
        min-width="440"
        :close-on-content-click="false"
    >
      <v-card v-if="collection.totalItems === 0" height="80" width="440" 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 width="440">
        <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
            >
              <strong>{{item.menuKey}}</strong> - {{item.label}}
            </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 {ref} from "@vue/reactivity";
import type {ComputedRef, Ref} from "@vue/reactivity";
import type {AnyJson} from "~/types/data";
import ApiResource from "~/models/ApiResource";
import UrlUtils from "~/services/utils/urlUtils";

const btn: Ref = ref(null)

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 UrlUtils.join(homeUrl, '#', list.entity ?? '', 'list', list.id ?? '')
}
</script>

<style scoped lang="scss">
  #activator {
    cursor: pointer;
  }

  #activator:hover {
    color: rgb(var(--var-theme-on-neutral)) !important;
  }

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