<template>
  <div class="d-flex justify-end py-0 py-sm-2">
    <v-btn
      class="d-none d-md-block"
      :aria-label="t('pages.login.toolbar.toggleTheme')"
      color="grey-darken-1"
      :icon="mdiPaletteOutline"
      size="small"
      variant="text"
      @click="toggleTheme"
    ></v-btn>
    <v-menu location="bottom end">
      <template #activator="{ props: menuActivatorProps }">
        <v-btn
          v-bind="menuActivatorProps"
          :aria-label="t('pages.login.toolbar.selectLocale')"
          color="grey-darken-1"
          :icon="mdiTranslate"
          size="small"
          variant="text"
        ></v-btn>
      </template>
      <v-list role="none" density="compact">
        <v-list-item
          v-for="localeOption in localeOptions"
          :key="localeOption"
          :active="localeOption === props.locale"
          @click="handleSelectLocale(localeOption)"
        >
          <v-list-item-title>{{ localeLabels[localeOption] ?? localeOption }}</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </div>
</template>

<script setup lang="ts">
import { mdiPaletteOutline, mdiTranslate } from '@mdi/js'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useTheme } from 'vuetify'
import { getNextThemeName } from '@/utils/theme'

interface Props {
  locale?: string
  locales?: string[]
  localeLabels?: Record<string, string>
}

const props = withDefaults(defineProps<Props>(), {
  locale: 'zh-TW',
  locales: () => ['zh-TW', 'en-US'],
  localeLabels: () => ({
    'en-US': 'English',
    'zh-TW': '中文',
  }),
})

const emit = defineEmits(['change-locale', 'toggle-layout'])

const { t } = useI18n()
const theme = useTheme()

const availableThemeNames = computed(() =>
  Object.keys(theme.themes.value ?? {}).filter((name) => name.startsWith('theme'))
)

function toggleTheme() {
  const names = availableThemeNames.value
  if (names.length === 0) return

  const current = theme.global.name.value
  const next = getNextThemeName(names, current)
  if (!next) return
  theme.change(next)
}

const localeOptions = computed(() =>
  props.locales.length > 0 ? props.locales : ['zh-TW', 'en-US']
)

function handleSelectLocale(locale: string) {
  if (locale === props.locale) return
  emit('change-locale', locale)
}
</script>
