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 androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import com.kaixed.kchat.R
import com.kaixed.kchat.data.objectbox.ObjectBox.get
import com.kaixed.kchat.data.objectbox.entity.UserInfo
import com.kaixed.kchat.data.objectbox.entity.UserInfo_
import com.kaixed.kchat.databinding.ActivityLoginBinding
import com.kaixed.kchat.ui.base.BaseActivity
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.UserViewModel
import com.tencent.mmkv.MMKV
import io.objectbox.Box
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginActivity : BaseActivity<ActivityLoginBinding>() {

    private val userViewModel: UserViewModel by viewModels()


    private var previousKeyboardHeight = 0
    private var loginByUsername = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

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

        initView()
        setListener()

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

            login(username, password)
        }

        getKeyboardHeight()
    }

    private fun login(username: String, password: String) {
        if (!loginByUsername) {
            binding.etUsername.text.toString().length != 11
            toast("请输入正确的手机号码")
            return
        }
        if (username.isEmpty() || password.isEmpty()) {
            toast("请输入${if (loginByUsername) "用户名" else "手机号"}或密码")
        }
        userViewModel.loginResult.observe(this) { loginResult ->
            loginResult.onSuccess {
                navigateToMain()
            }
            loginResult.onFailure {
                toast(it.message.toString())
            }
        }
        if (loginByUsername) {
            userViewModel.loginByUsername(username, password)
        } else {
            userViewModel.loginByTelephone(username, password)
        }
    }

    private fun initView() {
        setView()
    }

    private fun setListener() {
        binding.ivClose.setOnClickListener {
            finish()
        }

        binding.tvChangeLoginWay.setOnClickListener {
            loginByUsername = !loginByUsername
            setView()
        }
    }

    private fun setView() {
        binding.tvTitle.text = if (loginByUsername) "用户名登录" else "手机号登录"
        binding.etUsername.hint = if (loginByUsername) "请填写用户名" else "请填写手机号"
        binding.tvUsername.text = if (loginByUsername) "用户名" else "手机号"
        binding.tvChangeLoginWay.text = if (loginByUsername) "手机号登录" else "用户名登录"
        binding.tvTip.text =
            if (loginByUsername) "上述账号仅用于登陆验证" else "上述手机号仅用于登陆验证"
    }

    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)
                }
            }
        }
    }

    private val textWatcher = object : 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) {

            val isInputValid =
                binding.etUsername.text.isNotEmpty() && binding.etPassword.text.isNotEmpty()

            binding.tvLogin.apply {
                setTextColor(
                    if (isInputValid) {
                        ContextCompat.getColor(
                            this@LoginActivity,
                            R.color.white
                        )
                    } else {
                        Color.parseColor("#B4B4B4")
                    }
                )
                background = createDrawable(
                    if (isInputValid) {
                        ContextCompat.getColor(
                            this@LoginActivity,
                            R.color.green
                        )
                    } else {
                        Color.parseColor("#E1E1E1")
                    },
                    dpToPx(8)
                )
            }
        }
    }

    private fun navigateToMain() {
        toast("登录成功")
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    override fun inflateBinding(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }
}
