<script setup lang="ts">
import { useSystemLanguageStore } from '@/store/modules/system-language'
import { ref } from 'vue'
// import { useI18n } from 'vue-i18n'
import { Up, Translate, Down } from '@icon-park/vue-next'
import { useRouter } from 'vue-router'

interface Props {
  arrowDirection: 'top' | 'bottom'
  btnBgColor?: string
}

const { arrowDirection = 'bottom', btnBgColor = '#f4f5f5' } = defineProps<Props>()

const systemLanguageStore = useSystemLanguageStore()
// const { locale } = useI18n()
const router = useRouter()

const isShowLanguagePopover = ref(false)

function handleLanguageOptionsUpdateShow(value: boolean) {
  if (value) {
    isShowLanguagePopover.value = true
  } else {
    isShowLanguagePopover.value && (isShowLanguagePopover.value = false)
  }
}

function handleLanguageOptionSelect(key: I18n.LangType) {
  systemLanguageStore.updateCurrentLanguageInfo(key)

  router.go(0)
  // locale.value = key

  isShowLanguagePopover.value = false
}
</script>

<template>
  <n-popover
    placement="bottom"
    trigger="hover"
    class="!p-[10px]"
    :show-arrow="false"
    :show="isShowLanguagePopover"
    @update:show="handleLanguageOptionsUpdateShow"
  >
    <template #trigger>
      <button
        class="flex w-full items-center rounded-[6px] bg-[#f4f5f5] px-[12px] py-[6px] transition hover:bg-[#eceded]"
        :style="{ backgroundColor: btnBgColor }"
      >
        <Translate theme="outline" size="16" fill="#000dff" :stroke-width="3" />

        <div class="ml-[10px] flex flex-1 items-center justify-between">
          <span>{{ systemLanguageStore.currentLanguageInfo.label }}</span>
          <Up
            v-if="arrowDirection === 'top'"
            class="transition-[rotate] duration-300 ease-in-out"
            :class="{ 'rotate-180': isShowLanguagePopover }"
            theme="outline"
            size="21"
            fill="#333"
            :stroke-width="3"
          />

          <Down
            v-else
            theme="outline"
            size="21"
            fill="#333"
            :stroke-width="3"
            class="transition-[rotate] duration-300 ease-in-out"
            :class="{ 'rotate-180': isShowLanguagePopover }"
          />
        </div>
      </button>
    </template>

    <ul class="select-none">
      <li
        v-for="langItem in systemLanguageStore.languageOptions"
        :key="langItem.key"
        class="relative mb-[6px] cursor-pointer bg-[#f3f3f5] px-[20px] py-[4px] text-center transition last:mb-0 hover:bg-[#e7e7e7]"
        @click="handleLanguageOptionSelect(langItem.key as I18n.LangType)"
      >
        {{ langItem.label }}

        <i
          v-show="langItem.key === systemLanguageStore.currentLanguageInfo.key"
          class="iconfont icon-xuanze text-theme-color absolute bottom-0 right-0 text-[14px]"
        ></i>
      </li>
    </ul>
  </n-popover>
</template>
