import { ss } from '@/utils/storage'
import { defineStore } from 'pinia'
import { defaultLocale } from '@/locales/index'

interface SystemLanguageState {
  currentLanguageInfo: {
    key: I18n.LangType
    label: string
  }

  languageOptions: {
    key: string
    label: string
  }[]
}

const defaultLanguageOptions = [
  {
    label: '中文简体',
    key: 'zh-CN',
  },
  {
    label: '中文繁體',
    key: 'zh-HK',
  },
  {
    label: 'English',
    key: 'en',
  },
]

const localeKey = ss.get('i18nextLng') || defaultLocale

export const useSystemLanguageStore = defineStore('system-language-store', {
  state: (): SystemLanguageState => ({
    currentLanguageInfo: {
      key: localeKey,
      label: defaultLanguageOptions.find((optionItem) => optionItem.key === localeKey)!.label,
    },

    languageOptions: defaultLanguageOptions,
  }),
  getters: {
    currentLanguage(state): I18n.LangType {
      return state.currentLanguageInfo.key
    },
    isEnglishLanguage(state) {
      return state.currentLanguageInfo.key === 'en'
    },
  },
  actions: {
    updateCurrentLanguageInfo(key: I18n.LangType) {
      if (this.currentLanguageInfo.key === key) return ''

      ss.set('i18nextLng', key)

      this.currentLanguageInfo = this.languageOptions.find((optionItem) => optionItem.key === key) as {
        key: I18n.LangType
        label: string
      }
    },
  },
})
