package com.kaixed.kchat.ui.activity

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
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.ActivityRenameBinding
import com.kaixed.kchat.ui.base.BaseActivity
import com.kaixed.kchat.utils.Constants.MMKV_USER_SESSION
import com.kaixed.kchat.utils.Constants.NICKNAME_KEY
import com.kaixed.kchat.utils.ConstantsUtil.getNickName
import com.kaixed.kchat.utils.ConstantsUtil.getUsername
import com.kaixed.kchat.utils.WidgetUtil
import com.kaixed.kchat.viewmodel.UserViewModel
import com.tencent.mmkv.MMKV
import io.objectbox.Box

class RenameActivity : BaseActivity<ActivityRenameBinding>() {

    private val userInfoBox: Box<UserInfo> by lazy { get().boxFor(UserInfo::class.java) }

    private val userViewModel: UserViewModel by viewModels()

    private var oldNickname: String = ""

    private var updateSucceed = false


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

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

        oldNickname = getNickName()

        val nickname = oldNickname
        var enable = false

        binding.etNickname.setText(nickname)

        binding.etNickname.addTextChangedListener(
            afterTextChanged = { et ->
                val nowNickname = getNickName()
                enable = et.toString() != nowNickname
                binding.ctb.setBtnEnable(et.toString() != nowNickname)
            }
        )

        binding.ctb.setOnBtnClickListener {
            if (enable) {
                updateNicknamesByCondition(binding.etNickname.text.toString(), getUsername())
            }
        }
    }

    private fun updateNicknamesByCondition(newNickname: String, username: String) {
        binding.ctb.setBtnEnable(false)
        val dialog = WidgetUtil.showLoadingDialog(this, "正在保存")
        dialog.show()
        userViewModel.changeNickname(username, newNickname).observe(this) { result ->
            if (result) {
                val user = userInfoBox
                    .query(UserInfo_.username.equal(username))
                    .build()
                    .findFirst()

                MMKV.mmkvWithID(MMKV_USER_SESSION).putString(NICKNAME_KEY, newNickname)

                user?.nickname = newNickname

                if (user != null) {
                    userInfoBox.put(user)
                }
                binding.etNickname.setText(newNickname)
                updateSucceed = true
            } else {
                updateSucceed = false
                binding.etNickname.setText(oldNickname)
            }
            binding.etNickname.setSelection(newNickname.length)
        }
        Handler(Looper.getMainLooper()).postDelayed({
            dialog.dismiss()
            toast(if (updateSucceed) "更新成功" else "更新失败")
        }, 800)
    }

    override fun onResume() {
        super.onResume()
        binding.etNickname.setText(getNickName())
    }
}