package com.assimilate.alltrans.curview

import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import androidx.core.content.ContextCompat.getColor
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.model.Language
import com.assimilate.alltrans.model.LanguagesConstants
import com.assimilate.alltrans.model.PreferenceLanguageUtils
import com.assimilate.alltrans.databinding.LayoutSusChangelanBinding

class LanguageSelectorView(private val context: Context) {

    private val windowManager: WindowManager =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private var binding: LayoutSusChangelanBinding? = null
    private var lastTranslateLanguage = false
    private lateinit var fullScreenView: View

    fun createFloatingView() {

        // 添加全屏透明视图,点击区域外关闭
        fullScreenView = View(context)
        val fullScreenLayoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            },
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )

        fullScreenLayoutParams.gravity = Gravity.TOP or Gravity.LEFT
        windowManager.addView(fullScreenView, fullScreenLayoutParams)

        // 使用ViewBinding来加载自定义的布局
        binding = LayoutSusChangelanBinding.inflate(LayoutInflater.from(context))

        // 获取屏幕的高度
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val screenHeight = displayMetrics.heightPixels

        // 设置布局参数
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            screenHeight * 3 / 4, // 高度设置为屏幕的四分之三
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )

        // 设置悬浮窗的位置
        params.gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL

        initView()
        initClick()
        initAllList()

        // 将布局添加到window
        windowManager.addView(binding?.root, params)
        // 设置触摸监听器
        fullScreenView.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                removeFloatingView()
                true
            } else {
                false
            }
        }

    }

    private fun initView() {

        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(context, ArrayList(recentLanguages)) { _, language ->
                    Log.d("LanguageChange", language.language)
                    if (lastTranslateLanguage) {
                        PreferenceLanguageUtils.putString("language_target", language.language)
                        removeFloatingView()
                    } else {
                        PreferenceLanguageUtils.putString("language_source", language.language)
                        removeFloatingView()
                    }
                    PreferenceLanguageUtils.addRecentLanguage(language)
                    binding?.tvChangeSource?.text =
                        PreferenceLanguageUtils.getString("language_source")
                    binding?.tvChangeTarget?.text =
                        PreferenceLanguageUtils.getString("language_target")
                    updateRecentLanguages()
                }
            binding?.listLanCommon5?.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            binding?.listLanCommon5?.adapter = recentAdapter
        }
    }

    private fun initClick() {
        binding?.tvChangeSource?.setOnClickListener {
            lastTranslateLanguage = false
            binding?.tvChangeSource?.setTextColor(getColor(context, R.color.main_text_ff0e8ce8))
            binding?.tvChangeTarget?.setTextColor(getColor(context, R.color.main_text_ff1f1724))
        }
        binding?.tvChangeTarget?.setOnClickListener {
            lastTranslateLanguage = true
            binding?.tvChangeSource?.setTextColor(getColor(context, R.color.main_text_ff1f1724))
            binding?.tvChangeTarget?.setTextColor(getColor(context, 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, "hover")

            removeFloatingView()
        }

    }

    private fun initAllList() {
        val languages: ArrayList<Language> = LanguagesConstants.getInstance().getList(context)
        if (languages.isNotEmpty()) {
            val adapter = LanguageAdapter(context, languages) { _, language ->
                Log.d("LanguageChange", language.language)
                if (lastTranslateLanguage) {
                    FirebaseAnalyticsHelper.languageFromEvent(
                        MyApp.Config.CLICK_FROM,
                        "hover_target"
                    )
                    PreferenceLanguageUtils.putString("language_target", language.language)
                    removeFloatingView()
                } else {
                    FirebaseAnalyticsHelper.languageFromEvent(
                        MyApp.Config.CLICK_FROM,
                        "hover_source"
                    )
                    PreferenceLanguageUtils.putString("language_source", language.language)
                    removeFloatingView()
                }
                PreferenceLanguageUtils.addRecentLanguage(language)
                binding?.tvChangeSource?.text = PreferenceLanguageUtils.getString("language_source")
                binding?.tvChangeTarget?.text = PreferenceLanguageUtils.getString("language_target")
                updateRecentLanguages()
            }
            binding?.listLanguages?.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            binding?.listLanguages?.adapter = adapter
        }
    }

    private fun removeFloatingView() {
        binding?.root?.let {
            windowManager.removeView(it)
            windowManager.removeView(fullScreenView)
        }
        binding = null
    }


}
