package com.example.defenseapplication.utils

import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.os.Build
import android.os.LocaleList
import java.util.Locale

enum class AppLanguage(val code: String, val locale: Locale) {
    ENGLISH("en_US", Locale.US),
    SIMPLIFIED_CHINESE("zh_CN", Locale.SIMPLIFIED_CHINESE);

    companion object {
        fun fromCode(code: String): AppLanguage {
            return values().find { it.code == code } ?: SIMPLIFIED_CHINESE
        }
    }
}

object LanguageUtil {

    private const val PREF_NAME = "language_pref"
    private const val KEY_LANGUAGE = "selected_language"

    @JvmStatic
    var currentLanguage: AppLanguage = AppLanguage.SIMPLIFIED_CHINESE
        private set

    /**
     * 初始化语言，从持久化中恢复
     */
    fun init(context: Context) {
        val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        var code = prefs.getString(KEY_LANGUAGE, null)
        if (code == null) {
            // 兼容旧数据：尝试从 app_lang_pref 读取（LanguageHeaderManager 旧存储路径）
            val oldPrefs = context.getSharedPreferences("app_lang_pref", Context.MODE_PRIVATE)
            code = oldPrefs.getString("selected_language", AppLanguage.SIMPLIFIED_CHINESE.code)
                ?: AppLanguage.SIMPLIFIED_CHINESE.code
            // 迁移到新存储路径
            prefs.edit().putString(KEY_LANGUAGE, code).apply()
        }
        currentLanguage = AppLanguage.fromCode(code)
    }

    /**
     * 切换语言，同时更新 app locale 和 HTTP header
     * @param language AppLanguage.ENGLISH 或 AppLanguage.SIMPLIFIED_CHINESE
     */
    fun switchLanguage(context: Context, language: AppLanguage) {
        currentLanguage = language
        saveLanguage(context, language.code)
    }

    /**
     * 兼容旧代码：使用字符串 "zh" / "en" 切换
     */
    fun switchLanguage(context: Context, language: String) {
        val appLang = when (language) {
            "zh" -> AppLanguage.SIMPLIFIED_CHINESE
            else -> AppLanguage.ENGLISH
        }
        switchLanguage(context, appLang)
    }

    /**
     * 获取当前设置的语言代码 "zh" / "en"
     */
    fun getCurrentLanguage(context: Context): String {
        return currentLanguage.name.lowercase().let {
            if (it.contains("chinese")) "zh" else "en"
        }
    }

    /**
     * 获取 HTTP header 的语言值 "en_US" / "zh_CN"
     */
    fun getLanguageHeaderValue(): String = currentLanguage.code

    /**
     * 保存语言设置
     */
    private fun saveLanguage(context: Context, languageCode: String) {
        val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        prefs.edit().putString(KEY_LANGUAGE, languageCode).apply()
    }

    /**
     * 判断当前是否是中文
     */
    fun isChinese(context: Context): Boolean {
        return currentLanguage == AppLanguage.SIMPLIFIED_CHINESE
    }

    /**
     * 获取本地化的 Context（在 attachBaseContext 中调用）
     */
    fun attachBaseContext(context: Context): Context {
        val locale = getSavedLocale(context)
        return createLocalizedContext(context, locale)
    }

    /**
     * 读取已保存的语言 locale（attachBaseContext 中使用，此时 currentLanguage 可能尚未初始化）
     */
    private fun getSavedLocale(context: Context): Locale {
        val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        val code = prefs.getString(KEY_LANGUAGE, AppLanguage.SIMPLIFIED_CHINESE.code)
            ?: AppLanguage.SIMPLIFIED_CHINESE.code
        return AppLanguage.fromCode(code).locale
    }

    /**
     * 创建本地化的 Context
     */
    private fun createLocalizedContext(context: Context, locale: Locale): Context {
        Locale.setDefault(locale)

        val resources = context.resources
        val configuration = resources.configuration

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val localeList = LocaleList(locale)
            configuration.setLocales(localeList)
            context.createConfigurationContext(configuration)
        } else {
            configuration.locale = locale
            resources.updateConfiguration(configuration, resources.displayMetrics)
            context
        }
    }

    /**
     * 更新应用语言（用于在 Activity 中动态切换）
     */
    fun updateResources(context: Context): Context {
        val locale = currentLanguage.locale
        Locale.setDefault(locale)

        val resources = context.resources
        val configuration = resources.configuration

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val localeList = LocaleList(locale)
            configuration.setLocales(localeList)
        } else {
            configuration.locale = locale
        }

        resources.updateConfiguration(configuration, resources.displayMetrics)
        return context
    }

    /**
     * 获取语言显示名称
     */
    fun getLanguageDisplayName(language: String): String {
        return when (language) {
            "zh" -> "中文"
            "en" -> "English"
            else -> "中文"
        }
    }
}
