<template>
  <v-menu
    v-model="menu"
    location="bottom"
    offset="5px"
    :close-on-content-click="false"
  >
    <template #activator="{ props }">
      <v-list class="pa-0">
        <v-list-item
          v-bind="props"
          :key="props.title"
          :prepend-icon="prop.icon"
          append-icon="mdi-chevron-down"
          :to="props.route"
          class="text-subtitle-2 font-weight-bold"
        >
          <v-list-item-title class="text-truncate">
            {{ name || `Select ${prop.title}` }}
          </v-list-item-title>
        </v-list-item>
      </v-list>
    </template>

    <v-card width="300px" rounded="lg" class="pa-4">
      <span class="text-subtitle-2 font-weight-bold">
        Switch {{ prop.title }} context
      </span>
      <v-text-field
        v-model="search"
        @keydown.enter="emit('search')"
        density="compact"
        width="100%"
        hide-details
        class="mb-2"
      >
        <template #prepend-inner>
          <v-icon>mdi-magnify</v-icon>
        </template>
      </v-text-field>
      <v-divider />
      <v-list class="pa-0 my-2" density="compact" max-height="200px">
        <v-list-item
          density="compact"
          class="text-caption font-weight-bold"
          v-for="item in prop.items"
          :key="item.value"
          @click="selectItem(item.value)"
        >
          <v-icon size="16" class="mr-2">
            {{ selected === item.value ? "mdi-check" : "" }}
          </v-icon>

          {{ item.text }}
        </v-list-item>
      </v-list>

      <slot name="footer"></slot>
    </v-card>
  </v-menu>
</template>

<script setup lang="ts">
const prop = defineProps({
  title: {
    type: String,
    required: true,
    default: "app",
  },
  items: {
    type: Array as PropType<Array<Record<string, any>>>,
    required: false,
    default: () => [],
  },
  icon: {
    type: String,
    required: false,
    default: "mdi-domain",
  },
  logo: {
    type: String,
    required: false,
    default: "",
  },
});

const menu = defineModel<boolean>("menu", { required: false, default: false });
const selected = defineModel<string>("selected", {
  required: false,
  default: "",
});
const search = defineModel<string>("search", {
  required: false,
  default: "",
});

const emit = defineEmits(["search", "select"]);

const name = computed(() => {
  return prop.items.find((item) => item.value === selected.value)?.text ?? "";
});

const selectItem = (value: string) => {
  selected.value = value;
  menu.value = false;
  emit("select", value);
};
</script>
