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


interface AppSettings {
  fontSize: number
  locale: string
}

const defaultFontSize = 16
const minFontSize = 10
const maxFontSize = 22
const fontSizeStep = 2

const defaultSettings: AppSettings = {
  fontSize: defaultFontSize,
  locale: 'en-US'
}

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 canIncrease = computed(() => currentFontSize.value < maxFontSize)
  const canDecrease = computed(() => currentFontSize.value > minFontSize)
  
  const supportLocale = [
    { value: 'en-US', label: 'English' },
    { value: 'ru-RU', label: 'Русский' }
  ]
  
  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 = () => {
    if (settings.value.locale && i18nLocale) {
      i18nLocale.value = settings.value.locale
    }
  }

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

  const updateLocale = async (newLocale: string) => {
    settings.value.locale = newLocale
    applyLocale()
    await saveSettings()
  }

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

  const updateSettings = async (newSettings: Partial<AppSettings>) => {
    settings.value = { ...settings.value, ...newSettings }
    updateCssVariable()
    applyLocale()
    await saveSettings()
  }

  const clampFontSize = (size: number) => 
    Math.max(minFontSize, Math.min(size, maxFontSize))

  const increaseFontSize = async () => {
    const newSize = clampFontSize(currentFontSize.value + fontSizeStep)
    await updateSettings({ fontSize: newSize })
  }

  const decreaseFontSize = async () => {
    const newSize = clampFontSize(currentFontSize.value - fontSizeStep)
    await updateSettings({ fontSize: newSize })
  }

  watch(() => authStore.isAuth, (newVal) => {
    if (newVal !== undefined) void init()
  }, { immediate: true })

  return {
    settings,
    supportLocale,
    isInit,
    currentFontSize,
    canIncrease,
    canDecrease,
    init,
    increaseFontSize,
    decreaseFontSize,
    updateSettings,
    updateLocale
  }
})
