<template>
  <v-menu :close-on-content-click="false" v-model="isOpen">
    <template #activator="{ props }">
      <v-btn class="!tw:me-0" v-bind="props">
        <v-avatar density="compact" color="primary" class="tw:mr-2">
          {{ avatar }}
        </v-avatar>
        <v-icon>mdi-chevron-down</v-icon>
      </v-btn>
    </template>
    <v-list class="tw:pb-0" :key="locale">
      <v-list-item>
        <template #prepend>
          <v-icon>mdi-translate</v-icon>
        </template>
        <v-list-item-title>
          <v-btn-toggle v-model="locale" mandatory @click="storeLocale">
            <v-btn :key="locale" v-for="locale in locales" :value="locale">
              <span v-html="localeFlags[locale]"></span>
            </v-btn>
          </v-btn-toggle>
        </v-list-item-title>
      </v-list-item>
      <v-divider />
      <v-list-item @click="refreshQueries">
        <template #prepend>
          <v-icon>mdi-refresh</v-icon>
        </template>
        <v-list-item-title>
          {{ $t("core.refreshAllQueries") }}</v-list-item-title
        >
      </v-list-item>
      <v-divider />

      <v-list-item @click="toggleTheme">
        <template #prepend>
          <v-icon>mdi-theme-light-dark</v-icon>
        </template>
        <v-list-item-title>{{ $t("core.toggle_theme") }}</v-list-item-title>
      </v-list-item>
      <v-list-item v-if="isWinter()" @click="toggleSnow">
        <template #prepend>
          <v-icon>mdi-snowflake</v-icon>
        </template>
        <v-list-item-title>{{ $t("core.toggle_snow") }}</v-list-item-title>
      </v-list-item>
      <div id="appUserMenu" ref="appUserMenu">
        <template
          v-for="item in pageNavigation.userMenuItems"
          :key="item.route"
        >
          <v-list-item
            :key="locale"
            v-if="item.slotType !== 'inline'"
            :disabled="activeRouteName === item.route || !item.route"
            :active="activeRouteName === item.route"
            :value="item.route || ''"
            color="primary"
            class="nav-link"
            link
            @click="navigate(item)"
          >
            <!-- item prepend icon -->
            <template v-if="item.icon" #prepend>
              <v-icon :icon="item.icon" />
            </template>
            <v-list-item-title v-if="item.title">{{
              item.title
            }}</v-list-item-title>
          </v-list-item>
          <template v-else>
            <v-list-group v-if="item.icon || item.title">
              <template v-slot:activator="{ props }">
                <v-list-item
                  v-bind="props"
                  :prepend-icon="item.icon"
                  :title="item.title"
                ></v-list-item>
              </template>
              <WidgetsLayoutLoader
                v-if="compositions[item.compositionId]"
                :widgets-layout="compositions[item.compositionId].widgetsLayout"
                slot-type="inline"
                :slot-layout="compositions[item.compositionId].slotLayout"
                :max-height="availableComponentHeight"
              />
            </v-list-group>
            <template v-else>
              <WidgetsLayoutLoader
                v-if="compositions[item.compositionId]"
                :widgets-layout="compositions[item.compositionId].widgetsLayout"
                slot-type="inline"
                :max-height="availableComponentHeight"
                :slot-layout="compositions[item.compositionId].slotLayout"
              />
            </template>
          </template>
        </template>
      </div>

      <v-divider />

      <v-list-item
        v-if="requireAuthentication"
        class="tw:bg-red-800! tw:text-white!"
        to="/logout"
        prepend-icon="mdi-logout"
        :title="$t('core.logout')"
      />
    </v-list>
  </v-menu>
</template>
<script setup lang="ts">
import localeFlags from "@racletteOrchestrator/assets/iconMappings/flags.json"
import { computed, useTemplateRef, onMounted, ref } from "vue"
import { useRouter } from "vue-router"
import useStateSubscriber from "@racletteOrchestrator/composables/useStateSubscriber"
import useUiState from "@racletteOrchestrator/composables/useUiState"
import { $store } from "@racletteCore"
import configService from "@racletteCore/lib/configService"
import { awaitTime, debounceHelper } from "@racletteCore/lib/dataHelper"
import useRouteState from "@racletteOrchestrator/composables/useRouteState"
import { DEFAULT_SLOT_NAME } from "@racletteOrchestrator/router/routeParserHelper"
import { useLocalStorage } from "@vueuse/core"
import WidgetsLayoutLoader from "../composition/WidgetsLayoutLoader.vue"
import {
  debounceHelper as asteroidsDebounceHelper,
  eggMe,
} from "@racletteCore/lib/easteregg"
import usePageNavigation, {
  type NavigationItem,
} from "@racletteOrchestrator/composables/usePageNavigation"
const appUserMenuRef = useTemplateRef("appUserMenu")
const availableComponentHeight = computed(
  () => appUserMenuRef?.value?.offsetHeight || 150,
)
const { locales } = configService.getI18nConfig()
const router = useRouter()
const asteroidsDebounce = asteroidsDebounceHelper(3)
const debounce = debounceHelper(1000)
const { state: user } = useStateSubscriber("user")
const { state: compositions } = useStateSubscriber("compositions")
const { locale, theme } = useUiState()
const { getCompositionLinkForSlotName } = useRouteState()

const userLanguage = useLocalStorage<string>("user-language", null)
const userTheme = useLocalStorage<string>("user-theme", null)
const showSnow = useLocalStorage<boolean>("show-snow", true)
const { state: pageNavigation } = usePageNavigation()

const isOpen = ref(false)
const canRefresh = ref(true)

const requireAuthentication = configService.getRequireAuthentication()
const isWinter = () => {
  const month = new Date().getMonth()
  if (month === 11 || month === 0) {
    return true
  }
  return false
}
const currentPageRoute = getCompositionLinkForSlotName(DEFAULT_SLOT_NAME)

const activeRouteName = computed(() => {
  const currentRoute = router.currentRoute.value
  const pageCompositionLinkValue = currentPageRoute?.value?.slotValue

  // consider dynamic pages
  if (currentRoute.name === "app.space.page") {
    return pageCompositionLinkValue || currentRoute.params.pageId
  }

  return pageCompositionLinkValue || currentRoute.name
})

const avatar = computed(() => {
  if (user.value?.avatar) {
    return user.value.avatar
  }
  let nameString = ""

  if (user.value.firstname) {
    nameString += user.value.firstname.substring(0, 1)
  }
  if (user.value.lastname) {
    nameString += user.value.lastname.substring(0, 1)
  }

  return nameString
})
const toggleTheme = () => {
  theme.value = theme.value === "light" ? "dark" : "light"
  userTheme.value = theme.value
}

const storeLocale = () => {
  userLanguage.value = locale.value
}

const refreshQueries = () => {
  openEgg()
  if (canRefresh.value) {
    $store.dispatch({
      type: "queries/execute",
      payload: {},
    })
    canRefresh.value = false
    debounce(() => {
      canRefresh.value = true
    })
  }
}

const navigate = (item: NavigationItem) => {
  isOpen.value = false
  item.navigateTo()
}

const openEgg = () =>
  asteroidsDebounce(() => {
    isOpen.value = false
    eggMe("asteroids")
  })
const toggleSnow = () => {
  showSnow.value = !showSnow.value
  eggMe("xmas")
}
onMounted(async () => {
  if (isWinter()) {
    await awaitTime(600)
    if (showSnow.value) {
      eggMe("xmas")
    }
  }
})
</script>
