<template>
  <v-menu v-if="organizations.length > 1">
    <template #activator="{ props }">
      <v-btn
        v-bind="props"
        variant="outlined"
        prepend-icon="mdi-domain"
        class="text-none"
      >
        {{ selectedOrganization?.name || 'Select Organization' }}
        <v-icon end>mdi-menu-down</v-icon>
      </v-btn>
    </template>
    <v-list>
      <v-list-item
        v-for="org in organizations"
        :key="org.id"
        :active="org.id === selectedOrgId"
        @click="selectOrganization(org.id)"
      >
        <v-list-item-title>
          <v-icon v-if="org.id === selectedOrgId" start size="small">mdi-check</v-icon>
          {{ org.name }}
        </v-list-item-title>
        <template #append>
          <v-chip size="small" variant="tonal">
            {{ org.apiKeys?.length || 0 }} keys
          </v-chip>
        </template>
      </v-list-item>
    </v-list>
  </v-menu>
  <v-chip v-else-if="organizations.length === 1" variant="outlined" prepend-icon="mdi-domain">
    {{ organizations[0].name }}
  </v-chip>
</template>

<script setup lang="ts">
import { useOrganizationSelector } from '~/composables/useOrganizationSelector'

const { organizations, selectedOrganization, selectedOrgId, selectOrganization } = useOrganizationSelector()
</script>
