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.keepmodel.Language
import com.assimilate.alltrans.keepmodel.LanguagesConstants
import com.assimilate.alltrans.keepmodel.PreferenceLanguageUtils
import com.assimilate.alltrans.databinding.ActivityLanguageChangeBinding
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 {
            withContext(Dispatchers.IO) {
                // 耗时操作
                initAllList()
            }
        }
        initClick()
    }

    private fun initSearch() {
        binding.chSearch.apply {
            // 获取关闭按钮的ImageView
            val closeButton = findViewById<ImageView>(androidx.appcompat.R.id.search_close_btn)

            // 设置关闭按钮一直可见
            closeButton.visibility = View.VISIBLE

            // 确保 SearchView 处于可点击状态
            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 {
                    (binding.listLanguages.adapter as LanguageAdapter).filter.filter(newText)
                    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() {
        val recentLanguages = PreferenceLanguageUtils.getRecentLanguages()
        if (recentLanguages.isNotEmpty()) {
            val recentAdapter = LanguageAdapter(this, ArrayList(recentLanguages)) { _, language ->
                Log.d("LanguageChange", language.language)
                if (lastTranslateLanguage) {
                    PreferenceLanguageUtils.putString("language_target", language.language)
                    onBackPressed()
                } else {
                    PreferenceLanguageUtils.putString("language_source", language.language)
                    onBackPressed()
                }
                PreferenceLanguageUtils.addRecentLanguage(language)
                binding.tvChangeSource.text = PreferenceLanguageUtils.getString("language_source")
                binding.tvChangeTarget.text = PreferenceLanguageUtils.getString("language_target")
                updateRecentLanguages()
            }
            binding.listLanCommon5.layoutManager =
                LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            binding.listLanCommon5.adapter = recentAdapter
        }
    }

    private fun initClick() {
        binding.ivChBack.setOnClickListener { onBackPressed() }
        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
            onBackPressed()
        }


    }

    private fun initAllList() {
        val languages: ArrayList<Language> = LanguagesConstants.getInstance().getList(this)
        if (languages.isNotEmpty()) {
            val adapter = LanguageAdapter(this, languages) { _, language ->
                Log.d("LanguageChange", language.language)
                if (lastTranslateLanguage) {
                    PreferenceLanguageUtils.putString("language_target", language.language)
                    FirebaseAnalyticsHelper.languageChooseEvent("target_" + language.language)
                    onBackPressed()
                } else {
                    PreferenceLanguageUtils.putString("language_source", language.language)
                    FirebaseAnalyticsHelper.languageChooseEvent("source_" + language.language)
                    onBackPressed()
                }
                PreferenceLanguageUtils.addRecentLanguage(language)
                binding.tvChangeSource.text = PreferenceLanguageUtils.getString("language_source")
                binding.tvChangeTarget.text = PreferenceLanguageUtils.getString("language_target")
                updateRecentLanguages()
            }
            binding.listLanguages.layoutManager =
                LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            binding.listLanguages.adapter = adapter
        }
    }

}
