<template>
  <main>
    <v-menu
      bottom
      left
      transition="slide-y-transition"
      :close-on-content-click="false"
      min-width="500"
    >
      <template #activator="{ on, attrs }">
        <span
          v-bind="attrs"
          class="ot-green--text"
          v-on="on"
        >
          {{ $t('my_list') }}
        </span>
      </template>
      <v-card scrollable>
        <v-card-title class="text-body-2 header-personnalized">
          <v-text-field
            dense
            clear-icon="header-personnalized"
            :loading="fetchState.pending"
            v-model="search"
            :label="$t('searchList')"
          />
        </v-card-title>
        <v-card-text class="ma-0 pa-0 mt-n3 header_menu">
          <v-list dense :subheader="true">
            <template v-for="(item, index) in filteredItems">
              <v-list-item
                :id="item.id"
                :key="index"
                :href="goOn(item)"
                router
                exact
              >
                <v-list-item-title>
                  {{item.label}} - <strong>{{item.menuKey}}</strong>
                </v-list-item-title>
              </v-list-item>
            </template>

          </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} from "@vue/reactivity";
import {AnyJson} from "~/types/data";
import ApiResource from "~/models/ApiResource";

// fetchOnServer: false,

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 item.label.toLowerCase().indexOf(search.value.toLowerCase()) >= 0
             ||item.menuKey.toLowerCase().indexOf(search.value.toLowerCase()) >= 0
    }
  )
})

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

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

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