package com.kaixed.kchat.ui.activity

import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.kaixed.kchat.R
import com.kaixed.kchat.databinding.ActivityLoginBinding
import com.kaixed.kchat.utils.Constants.KEYBOARD_HEIGHT_RATIO
import com.kaixed.kchat.utils.Constants.MMKV_COMMON_DATA
import com.kaixed.kchat.utils.Constants.MMKV_USER_SESSION
import com.kaixed.kchat.utils.DensityUtil.dpToPx
import com.kaixed.kchat.utils.DrawableUtil.createDrawable
import com.kaixed.kchat.viewmodel.LoginViewModel
import com.tencent.mmkv.MMKV

class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding

    private val mViewModel: LoginViewModel by viewModels()

    private var mmkv: MMKV? = null

    private var previousKeyboardHeight = 0

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

        mmkv = MMKV.mmkvWithID(MMKV_USER_SESSION)

        binding.etUsername.addTextChangedListener(textWatcher)
        binding.etPassword.addTextChangedListener(textWatcher)

        binding.tvLogin.setOnClickListener {
            val username = binding.etUsername.text.toString().trim()
            val password = binding.etPassword.text.toString().trim()

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "请输入用户名或密码", Toast.LENGTH_SHORT).show()
            }
            mViewModel.login(username, password).observe(this) { loginResult ->
                if (loginResult == null) {
                    runOnUiThread {
                        Toast.makeText(
                            this@LoginActivity,
                            "登录异常",
                            Toast.LENGTH_SHORT
                        )
                            .show()
                    }
                } else if ("200" == loginResult.code) {
                    mmkv!!.encode("username", loginResult.data.username)
                    mmkv!!.encode("nickname", loginResult.data.nickname)
                    mmkv!!.encode("nickname", loginResult.data.avatarUrl)
                    mmkv!!.encode("userLoginStatus", true)
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
                    navigateToMain()
                }
            }
        }

        getKeyboardHeight()
    }

    private fun getKeyboardHeight() {
        val rootLayout = binding.root

        rootLayout.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            rootLayout.getWindowVisibleDisplayFrame(rect)

            val screenHeight = rootLayout.rootView.height
            val keypadHeight = screenHeight - rect.bottom

            // 通过15%的屏幕高度差来判断是否为键盘
            if (keypadHeight > (screenHeight * KEYBOARD_HEIGHT_RATIO)) {
                if (keypadHeight != previousKeyboardHeight) {
                    previousKeyboardHeight = keypadHeight

                    val kv = MMKV.mmkvWithID(MMKV_COMMON_DATA)
                    kv.encode("keyboardHeight", keypadHeight)
                }
            }
        }
    }

    abstract class SimpleTextWatcher : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(s: Editable) {}
    }

    private var textWatcher: TextWatcher = object : SimpleTextWatcher() {

        override fun afterTextChanged(s: Editable) {
            super.afterTextChanged(s)
            if (s.isNotEmpty()) {
                if (binding.etUsername.text.isNotEmpty() && binding.etPassword.text.isNotEmpty()) {
                    binding.tvLogin.setTextColor(
                        ContextCompat.getColor(
                            this@LoginActivity,
                            R.color.white
                        )
                    )
                    binding.tvLogin.background =
                        createDrawable(
                            ContextCompat.getColor(this@LoginActivity, R.color.green),
                            dpToPx(this@LoginActivity, 8)
                        )
                } else {
                    binding.tvLogin.setTextColor(Color.parseColor("#B4B4B4"))
                    binding.tvLogin.background =
                        createDrawable(Color.parseColor("#E1E1E1"), dpToPx(this@LoginActivity, 8))
                }
            }
        }
    }

    private fun navigateToMain() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }
}
