import { ref, computed, inject, getCurrentInstance  } from 'vue'
import { defineStore } from 'pinia'
import { api } from 'boot/axios'
import { useAuthStore } from 'stores/auth'
import { useI18n } from 'vue-i18n'
import { Lang } from 'quasar'
import type { WebApp } from '@twa-dev/types'

const app = getCurrentInstance()
const isIOS = app?.appContext.config.globalProperties.$isIOS
const isMobile = app?.appContext.config.globalProperties.$isMobile

interface AppSettings {
  locale: string
  fontSize: number
  displayMode: 'full' | 'window'
  localeBot: string
  timeZoneBot: { tz: string, offset: number, offsetString: string }
}

const defaultFontSize = 16
const defaultDisplayMode = isIOS && isMobile ? 'full' : 'window'

const defaultSettings: AppSettings = {
  locale: 'en-US',
  fontSize: defaultFontSize,
  displayMode: defaultDisplayMode,
  localeBot: 'en-US',
  timeZoneBot: { tz: 'Europe/Moscow', offset: 3, offsetString: '+03:00' }
}

export const useSettingsStore = defineStore('settings', () => {
  const { locale: i18nLocale } = useI18n()
  const authStore = useAuthStore()
  const settings = ref<AppSettings>({ ...defaultSettings })
  const tg = inject<WebApp>('tg')

  const isInit = ref(false)

  const currentFontSize = computed(() => settings.value?.fontSize ?? defaultFontSize)
  
  const supportLocale = [
    { value: 'en-US', label: 'English' },
    { value: 'ru-RU', label: 'Русский' }
  ]

  const supportFontSizes = [
    { value: 12, label: 'settings__fontsize_small' },
    { value: 16, label: 'settings__fontsize_medium' },
    { value: 20, label: 'settings__fontsize_large' }
  ]

  const quasarLangMap: Record<string, string> = {
    'en-US': 'en-US',
    'ru-RU': 'ru'
  }

  const updateQuasarLang = async (locale: string) => {
    const quasarLang = quasarLangMap[locale] || 'en-US'
    
    try {
      const langModule = await import(
        `../../node_modules/quasar/lang/${quasarLang}.js`
      )
      Lang.set(langModule.default)
    } catch (e) {
      console.error('Quasar Error load locale:', quasarLang, e)
    }
  }
  
  const detectLocale = (): string => {
    const localeMap = {
      ru: 'ru-RU',
      en: 'en-US'
    } as const satisfies Record<string, string>

    type LocaleCode = keyof typeof localeMap

    const normLocale = (locale?: string): string | undefined => {
      if (!locale) return undefined
      const code = locale.split('-')[0] as LocaleCode
      return localeMap[code] ?? undefined
    }

    const tgLang = tg?.initDataUnsafe?.user?.language_code
    const normalizedTgLang = normLocale(tgLang)

    return normalizedTgLang ?? normLocale(navigator.language) ?? 'en-US'
  }

  const updateCssVariable = () => {
    document.documentElement.style.setProperty(
      '--dynamic-font-size', 
      `${currentFontSize.value}px`
    )
  }

  const applyLocale = async () => {
    if (settings.value.locale && i18nLocale) {
      i18nLocale.value = settings.value.locale
      await updateQuasarLang(settings.value.locale)
    }
  }

  const init = async () => {
    if (authStore.isAuth) {
      try {
        const { data } = await api.get('/customer/settings')
        settings.value = {
          locale: data.data.locale || detectLocale(),
          fontSize: data.data.fontSize || defaultSettings.fontSize,
          displayMode: data.data.displayMode || defaultSettings.displayMode,
          localeBot: data.data.localeBot || detectLocale(),
          timeZoneBot: data.data.timeZoneBot || defaultSettings.timeZoneBot
        }
        if (!data.data.locale || !data.data.fontSize || !data.data.displayMode ||
            !data.data.localeBot || !data.data.timeZoneBot
           ) await saveSettings()
      } catch {
        settings.value.locale = detectLocale()
      }
    } else {
      settings.value = { 
        ...defaultSettings, 
        locale: detectLocale(),
        localeBot: detectLocale()
      }
    }
    updateCssVariable()
    await applyLocale()
    isInit.value = true
  }

  const saveSettings = async () => {
    const { data } = await api.put('/customer/settings', settings.value)
    if (data.data) settings.value = data.data
  }

  const updateSettings = async (newSettings: Partial<AppSettings>) => {
    settings.value = { ...settings.value, ...newSettings }
    updateCssVariable()
    await applyLocale()
    if (authStore.isAuth) await api.put('/customer/settings', settings.value)
  }

  return {
    settings,
    supportLocale,
    supportFontSizes,
    isInit,
    currentFontSize,
    init,
    updateSettings 
  }
})
