package com.app.input.breeze.board.uiactivity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.ad.tradpluslibrary.TPAdManager.loadAllAd
import com.app.input.breeze.board.BuildConfig
import com.app.input.breeze.board.R
import com.app.input.breeze.board.databinding.SettingsActivityBinding
import com.app.input.breeze.board.utils.AppUtils

class SettingsScreen : AppCompatActivity() {

    private lateinit var vb: SettingsActivityBinding
    private var inputMethodReceiver: BroadcastReceiver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vb = SettingsActivityBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(vb.root)
        loadAllAd(this)
        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
        }

        setupClickListeners()
        setupBottomNavigation()
        registerInputMethodReceiver()
        setupVersion()
    }

    private fun setupClickListeners() {
        // 启用键盘设置
        vb.layoutEnableKeyboard.setOnClickListener {
            startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS))
        }

        // 设置默认键盘（只有在第一步完成后才能点击）
        vb.layoutSetDefaultKeyboard.setOnClickListener {
            val isEnabled = AppUtils.checkEnable(this)
            if (isEnabled) {
                val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
                inputMethodManager.showInputMethodPicker()
            } else {
                // 如果第一步未完成，提示用户先完成第一步
                android.widget.Toast.makeText(
                    this,
                    getString(R.string.please_enable_keyboard_first),
                    android.widget.Toast.LENGTH_SHORT
                ).show()
            }
        }

        // 版本（不再需要点击事件，只显示版本号）
    }

    private fun setupBottomNavigation() {
        // 设置默认选中设置
        updateBottomNavState(R.id.nav_settings)

        // 主页点击
        findViewById<View>(R.id.nav_home).setOnClickListener {
            startActivity(Intent(this, MainActivity::class.java))
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            finish()
        }

        // 分类点击
        findViewById<View>(R.id.nav_category).setOnClickListener {
            startActivity(Intent(this, CategoryScreen::class.java))
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            finish()
        }

        // 设置点击
        findViewById<View>(R.id.nav_settings).setOnClickListener {
            // 已经在设置页，不需要操作
            updateBottomNavState(R.id.nav_settings)
        }
    }

    private fun updateBottomNavState(selectedId: Int) {
        val selectedColor = getColor(R.color.blue_primary)
        val unselectedColor = 0x80000000.toInt()

        val homeIcon = findViewById<android.widget.ImageView>(R.id.nav_home_icon)
        val homeText = findViewById<android.widget.TextView>(R.id.nav_home_text)
        val homeIndicator = findViewById<View>(R.id.nav_home_indicator)
        val categoryIcon = findViewById<android.widget.ImageView>(R.id.nav_category_icon)
        val categoryText = findViewById<android.widget.TextView>(R.id.nav_category_text)
        val categoryIndicator = findViewById<View>(R.id.nav_category_indicator)
        val settingsIcon = findViewById<android.widget.ImageView>(R.id.nav_settings_icon)
        val settingsText = findViewById<android.widget.TextView>(R.id.nav_settings_text)
        val settingsIndicator = findViewById<View>(R.id.nav_settings_indicator)

        when (selectedId) {
            R.id.nav_home -> {
                homeIcon.setColorFilter(selectedColor)
                homeText.setTextColor(selectedColor)
                homeIndicator.visibility = View.VISIBLE
                categoryIcon.setColorFilter(unselectedColor)
                categoryText.setTextColor(unselectedColor)
                categoryIndicator.visibility = View.GONE
                settingsIcon.setColorFilter(unselectedColor)
                settingsText.setTextColor(unselectedColor)
                settingsIndicator.visibility = View.GONE
            }
            R.id.nav_category -> {
                homeIcon.setColorFilter(unselectedColor)
                homeText.setTextColor(unselectedColor)
                homeIndicator.visibility = View.GONE
                categoryIcon.setColorFilter(selectedColor)
                categoryText.setTextColor(selectedColor)
                categoryIndicator.visibility = View.VISIBLE
                settingsIcon.setColorFilter(unselectedColor)
                settingsText.setTextColor(unselectedColor)
                settingsIndicator.visibility = View.GONE
            }
            R.id.nav_settings -> {
                homeIcon.setColorFilter(unselectedColor)
                homeText.setTextColor(unselectedColor)
                homeIndicator.visibility = View.GONE
                categoryIcon.setColorFilter(unselectedColor)
                categoryText.setTextColor(unselectedColor)
                categoryIndicator.visibility = View.GONE
                settingsIcon.setColorFilter(selectedColor)
                settingsText.setTextColor(selectedColor)
                settingsIndicator.visibility = View.VISIBLE
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 延迟更新，确保系统状态已更新
        Handler(Looper.getMainLooper()).postDelayed({
            updateKeyboardStatus()
        }, 300)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            // 当窗口获得焦点时更新状态（用户从系统设置返回时）
            Handler(Looper.getMainLooper()).postDelayed({
                updateKeyboardStatus()
            }, 200)
        }
    }

    private fun registerInputMethodReceiver() {
        inputMethodReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                // 当输入法状态改变时自动更新
                updateKeyboardStatus()
            }
        }
        val filter = IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED)
        registerReceiver(inputMethodReceiver, filter)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 注销广播接收器
        inputMethodReceiver?.let {
            try {
                unregisterReceiver(it)
            } catch (e: Exception) {
                // 忽略已注销的异常
            }
        }
    }

    private fun setupVersion() {
        // 从 BuildConfig 获取版本号
        vb.tvVersion.text = BuildConfig.VERSION_NAME
    }

    private fun updateKeyboardStatus() {
        val isEnabled = AppUtils.checkEnable(this)
        val isDefault = AppUtils.checkSetDefault(this)

        vb.tvEnableStatus.text = if (isEnabled) getString(R.string.enabled) else getString(R.string.not_enabled)
        vb.tvDefaultStatus.text = if (isDefault) getString(R.string.set_as_default) else getString(R.string.not_set_as_default)
        
        // 根据第一步是否完成来控制第二步的可用性和视觉状态
        if (isEnabled) {
            // 第一步已完成，第二步可用
            vb.layoutSetDefaultKeyboard.isEnabled = true
            vb.layoutSetDefaultKeyboard.alpha = 1.0f
        } else {
            // 第一步未完成，第二步禁用
            vb.layoutSetDefaultKeyboard.isEnabled = false
            vb.layoutSetDefaultKeyboard.alpha = 0.5f
        }
    }
}

