package com.assimilate.alltrans.viewui

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.assimilate.alltrans.MyApp
import com.assimilate.alltrans.R
import com.assimilate.alltrans.adapters.LanguageAdapter
import com.assimilate.alltrans.common.FirebaseAnalyticsHelper
import com.assimilate.alltrans.databinding.ActivityLanguageChangeBinding
import com.assimilate.alltrans.model.Language
import com.assimilate.alltrans.model.LanguagesConstants
import com.assimilate.alltrans.model.PreferenceLanguageUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LanguageChangeActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLanguageChangeBinding
    private var lastTranslateLanguage = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLanguageChangeBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initView()
        initSearch()
        lifecycleScope.launch {
            initAllList()
        }
        initClick()
    }

    private fun initSearch() {
        binding.chSearch.apply {
            val closeButton = findViewById<ImageView>(androidx.appcompat.R.id.search_close_btn)
            closeButton.visibility = View.VISIBLE
            isFocusable = true
            isIconified = false
            post { clearFocus() }

            setOnQueryTextListener(object :
                androidx.appcompat.widget.SearchView.OnQueryTextListener {
                override fun onQueryTextSubmit(query: String?): Boolean {
                    return false
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    // 确保 adapter 不为空并且是 LanguageAdapter 类型
                    val adapter = binding.listLanguages.adapter
                    if (adapter is LanguageAdapter) {
                        adapter.filter.filter(newText)
                    } else {
                        Log.e("LanguageChangeActivity", "Adapter is either null or not of type LanguageAdapter.")
                    }
                    return true
                }
            })

            closeButton.setOnClickListener {
                setQuery("", false)
                clearFocus()
                val imm =
                    context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(windowToken, 0)
            }
        }
    }

    private fun initView() {
        val intentT = intent
        if (intentT.getBooleanExtra("choose_t", false)) {
            lastTranslateLanguage = true
            binding.tvChangeSource.setTextColor(getColor(R.color.main_text_ff1f1724))
            binding.tvChangeTarget.setTextColor(getColor(R.color.main_text_ff0e8ce8))
        } else {
            lastTranslateLanguage = false
            binding.tvChangeSource.setTextColor(getColor(R.color.main_text_ff0e8ce8))
            binding.tvChangeTarget.setTextColor(getColor(R.color.main_text_ff1f1724))
        }

        binding.tvChangeSource.text = PreferenceLanguageUtils.getString("language_source")
        binding.tvChangeTarget.text = PreferenceLanguageUtils.getString("language_target")
        updateRecentLanguages()
    }

    private fun updateRecentLanguages() {
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                val recentLanguages = PreferenceLanguageUtils.getRecentLanguages()
                withContext(Dispatchers.Main) {
                    if (recentLanguages.isNotEmpty()) {
                        val recentAdapter = LanguageAdapter(
                            this@LanguageChangeActivity,
                            ArrayList(recentLanguages)
                        ) { _, language ->
                            handleLanguageSelection(language)
                        }
                        binding.listLanCommon5.layoutManager =
                            LinearLayoutManager(
                                this@LanguageChangeActivity,
                                LinearLayoutManager.VERTICAL,
                                false
                            )
                        binding.listLanCommon5.adapter = recentAdapter
                    }
                }
            }
        }
    }

    private fun handleLanguageSelection(language: Language) {
        // Log.d("LanguageChange", language.language)
        if (lastTranslateLanguage) {
            PreferenceLanguageUtils.putString("language_target", language.language)

            FirebaseAnalyticsHelper.languageChooseEvent(
                MyApp.Config.LAN_TARGET,
                "target_${language.language}"
            )
        } else {
            PreferenceLanguageUtils.putString("language_source", language.language)
            FirebaseAnalyticsHelper.languageChooseEvent(
                MyApp.Config.LAN_SOURCE,
                "source_${language.language}"
            )
        }

        FirebaseAnalyticsHelper.languageFromEvent(
            MyApp.Config.CLICK_FROM,
            if (lastTranslateLanguage) "home_target" else "home_source"
        )
        PreferenceLanguageUtils.addRecentLanguage(language)
        binding.tvChangeSource.text = PreferenceLanguageUtils.getString("language_source")
        binding.tvChangeTarget.text = PreferenceLanguageUtils.getString("language_target")
        updateRecentLanguages()
        finish()
    }

    private fun initClick() {
        binding.ivChBack.setOnClickListener { finish() }
        binding.tvChangeSource.setOnClickListener {
            lastTranslateLanguage = false
            binding.tvChangeSource.setTextColor(getColor(R.color.main_text_ff0e8ce8))
            binding.tvChangeTarget.setTextColor(getColor(R.color.main_text_ff1f1724))
        }
        binding.tvChangeTarget.setOnClickListener {
            lastTranslateLanguage = true
            binding.tvChangeSource.setTextColor(getColor(R.color.main_text_ff1f1724))
            binding.tvChangeTarget.setTextColor(getColor(R.color.main_text_ff0e8ce8))
        }

        binding.tvExchange.setOnClickListener {
            val currentSourceLanguage = PreferenceLanguageUtils.getString("language_source")
            val currentTargetLanguage = PreferenceLanguageUtils.getString("language_target")
            PreferenceLanguageUtils.putString("language_source", currentTargetLanguage)
            PreferenceLanguageUtils.putString("language_target", currentSourceLanguage)
            binding.tvChangeSource.text = currentTargetLanguage
            binding.tvChangeTarget.text = currentSourceLanguage
            FirebaseAnalyticsHelper.textTransSwitchEvent(MyApp.Config.CLICK_FROM, "home")

            finish()
        }
    }

    private suspend fun initAllList() {
        withContext(Dispatchers.IO) {
            val languages: ArrayList<Language> =
                LanguagesConstants.getInstance().getList(this@LanguageChangeActivity)
            withContext(Dispatchers.Main) {
                if (languages.isNotEmpty()) {
                    val adapter =
                        LanguageAdapter(this@LanguageChangeActivity, languages) { _, language ->
                            handleLanguageSelection(language)
                        }
                    binding.listLanguages.layoutManager =
                        LinearLayoutManager(
                            this@LanguageChangeActivity,
                            LinearLayoutManager.VERTICAL,
                            false
                        )
                    binding.listLanguages.adapter = adapter
                }
            }
        }
    }
}
