<template>
  <div ref="tenantSwitchButton" class="tenant-switcher-button">
    <div class="tenant-label" v-if="currentTenant && tenants.length === 1">
      <UiTenantImage :tenant="currentTenant" />
      <span>
        {{ currentTenant.label }}
      </span>
    </div>
    <BmsButton
      type="tertiary"
      @click="showTenantSwitcher = !showTenantSwitcher"
      v-else-if="tenants.length > 0"
    >
      <template #start>
        <UiTenantImage v-if="currentTenant" :tenant="currentTenant" />
      </template>
      <template #default>{{ tenantSwitcherLabel }}</template>
      <template #end>
        <ChevronDown />
      </template>
    </BmsButton>
    <UiTenantSwitcher
      :visible="showTenantSwitcher"
      :to="tenantSwitchButton"
      :tenants="tenants"
      :selectTenantPlaceholder="selectTenantPlaceholder"
      @removeFavoriteTenant="onRemoveFromFavoriteTenants"
      @changeTenant="onChangeTenant"
    />
  </div>
</template>

<script lang="ts" setup>
import { BmsButton, Tenant } from '@/index';
import { ChevronDown } from 'lucide-vue-next';
import UiTenantSwitcher from './UiTenantSwitcher.vue';
import {
  ComputedRef,
  Ref,
  computed,
  onBeforeUnmount,
  onMounted,
  ref,
  watch,
} from 'vue';
import UiTenantImage from './UiTenantImage.vue';

const props = withDefaults(
  defineProps<{
    currentTenant: Tenant | null;
    tenants: Tenant[];
    selectTenantLabel: string;
    selectTenantPlaceholder: string;
  }>(),
  {
    currentTenant: null,
    tenants: () => [],
    selectTenantLabel: '',
    selectTenantPlaceholder: '',
  },
);

const emits = defineEmits<{
  removeFavoriteTenant: [tenant: Tenant];
  changeTenant: [tenant: Tenant];
}>();

const tenantSwitchButton: Ref<HTMLElement | null> = ref(null);
const showTenantSwitcher: Ref<boolean> = ref<boolean>(false);

const tenantSwitcherLabel: ComputedRef<string> = computed(() => {
  return props.currentTenant
    ? props.currentTenant.label
    : props.selectTenantLabel;
});

onMounted(() => {
  document.body.addEventListener('click', tenantSwitcherCloser);
  document.body.addEventListener('keydown', tenantSwitcherCloser);
});

onBeforeUnmount(() => {
  window.removeEventListener('click', tenantSwitcherCloser);
  window.removeEventListener('keydown', tenantSwitcherCloser);
});

const tenantSwitcherCloser = (event: any) => {
  if (showTenantSwitcher.value && event) {
    if (
      (!event.target.closest('.ui-menu') &&
        !event.target.closest('.tenant-switcher-button')) ||
      (event.type === 'keydown' && event.key === 'Escape')
    ) {
      showTenantSwitcher.value = false;
    }
  }
};

const onChangeTenant = (tenant: Tenant) => {
  showTenantSwitcher.value = false;
  emits('changeTenant', tenant);
};

const onRemoveFromFavoriteTenants = (tenant: Tenant) => {
  emits('removeFavoriteTenant', tenant);
};

watch(
  () => props.tenants.length,
  () => {
    if (props.tenants.length === 1) {
      onChangeTenant(props.tenants[0]);
    }
  },
  { immediate: true },
);
</script>

<style lang="scss" scoped>
.tenant-label {
  padding: 8px;
  width: fit-content;
  display: flex;
  align-items: center;

  span {
    margin: 0 0.5em;
  }
}

.site-logo {
  width: 1em;
  height: 1em;
}
</style>
