import {
  DEFAULT_PUBLIC_LOCALE,
  detectExplicitPublicLocaleFromPath,
  normalizePublicLocale,
  stripPublicLocalePrefix,
  toPublicLocaleCode,
} from '~/utils/public-locales'
import { normalizePublicInternalPath } from '~/utils/public-routes'
import { resolvePublicLocaleSwitchPath, usePublicLocaleSwitchContextState } from '~/composables/usePublicLocaleSwitchContext'

export function usePublicLocale() {
  const route = useRoute()
  const { language } = usePublicPreferences()
  const localeSwitchContext = usePublicLocaleSwitchContextState()

  const explicitLocale = computed(() => detectExplicitPublicLocaleFromPath(route.path))
  const locale = computed(() => explicitLocale.value || DEFAULT_PUBLIC_LOCALE)
  const localeCode = computed(() => toPublicLocaleCode(locale.value))
  const pathWithoutLocale = computed(() => normalizePublicInternalPath(route.path, DEFAULT_PUBLIC_LOCALE))

  watch(
    explicitLocale,
    (value) => {
      if (value) {
        language.value = value
      }
    },
    { immediate: true },
  )

  function localizedPath(path, targetLocale = locale.value) {
    return normalizePublicInternalPath(path, targetLocale)
  }

  function localizedRoute(to, targetLocale = locale.value) {
    if (typeof to === 'string') {
      return localizedPath(to, targetLocale)
    }

    if (!to || typeof to !== 'object') {
      return to
    }

    if (to.path) {
      return {
        ...to,
        path: localizedPath(to.path, targetLocale),
      }
    }

    return to
  }

  function switchLocalePath(targetLocale) {
    return resolvePublicLocaleSwitchPath(localeSwitchContext.value, route.fullPath, targetLocale)
  }

  async function switchLocale(targetLocale) {
    const normalizedLocale = normalizePublicLocale(targetLocale)

    language.value = normalizedLocale

    if (normalizedLocale === locale.value) {
      return
    }

    await navigateTo(switchLocalePath(normalizedLocale))
  }

  return {
    explicitLocale,
    locale,
    localeCode,
    localizedPath,
    localizedRoute,
    pathWithoutLocale,
    switchLocale,
    switchLocalePath,
  }
}
