package com.kaixed.kchat.ui.activity

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
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.databinding.ActivityRegisterBinding
import com.kaixed.kchat.ui.base.BaseActivity
import com.kaixed.kchat.utils.DensityUtil.dpToPx
import com.kaixed.kchat.utils.DrawableUtil.createDrawable
import com.kaixed.kchat.viewmodel.UserViewModel
import io.objectbox.Box

class RegisterActivity : BaseActivity<ActivityRegisterBinding>() {

    private var tvContinueEnable: Boolean = false

    private val mViewModel: UserViewModel by viewModels()

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

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

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

        initView()

        setOnClickListener()
    }

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

        binding.tvContinue.setOnClickListener {
            onContinueClick()

        }
    }

    private fun onContinueClick() {
        if (!tvContinueEnable) return
        val telephone = binding.etUsername.text.toString().trim()
        if (telephone.length != 11) {
            toast("请输入正确的手机号")
            return
        }
        val nickname = binding.etNickname.text.toString().trim()
        val password = binding.etPassword.text.toString().trim()
        val avatarUrl = ""
        val signature = ""

        registerAccount(nickname, password, avatarUrl, signature, telephone)
    }

    private fun registerAccount(
        nickname: String,
        password: String,
        avatarUrl: String,
        signature: String,
        telephone: String
    ) {
        mViewModel.register(nickname, password, avatarUrl, signature, telephone)
            .observe(this) { registerResult ->
                when (registerResult?.code) {
                    "A0111" -> toast("用户名已存在，请重新注册")

                    "200" -> registerResult.data?.username?.let {
                        onRegisterSuccess(
                            it,
                            nickname,
                            telephone
                        )
                    }

                    else -> toast("系统服务器异常")
                }
            }
    }

    private fun onRegisterSuccess(username: String, nickname: String, telephone: String) {
        val userInfo = UserInfo(
            username = username,
            nickname = nickname,
            avatarUrl = "",
            signature = "",
            telephone = telephone
        )
        userInfoBox.put(userInfo)
        toast("注册成功，请前往登录界面登录")
        startActivity(Intent(this, LoginActivity::class.java))
        finish()
    }


    private fun initView() {
        setupTip()
        setOnEtChangeListener()
    }

    private fun setOnEtChangeListener() {
        val watcher = { _: Editable? -> changeContinueState() }
        binding.etUsername.addTextChangedListener(afterTextChanged = watcher)
        binding.etNickname.addTextChangedListener(afterTextChanged = watcher)
        binding.etPassword.addTextChangedListener(afterTextChanged = watcher)
    }

    private fun changeContinueState() {
        val allFieldsFilled = binding.etNickname.text.toString().isNotEmpty() &&
                binding.etUsername.text.toString().isNotEmpty() &&
                binding.etPassword.text.toString().isNotEmpty()

        tvContinueEnable = allFieldsFilled

        if (allFieldsFilled) {
            setContinueButtonState(
                ContextCompat.getColor(this, R.color.white),
                ContextCompat.getColor(this, R.color.green)
            )
        } else {
            setContinueButtonState(
                Color.parseColor("#B4B4B4"),
                Color.parseColor("#E1E1E1")
            )
        }
    }

    private fun setContinueButtonState(textColor: Int, backgroundColor: Int) {
        binding.tvContinue.setTextColor(textColor)
        binding.tvContinue.background = createDrawable(
            backgroundColor, dpToPx(this, 8)
        )
    }

    private fun setupTip() {
        val clickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                toast("暂未编写")
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = Color.parseColor("#576B95")
                ds.isUnderlineText = false
            }
        }

        val spannableString =
            SpannableString("我已阅读并同意《软件许可及服务协议》\n本页面收集的信息仅用于注册账户")
        spannableString.setSpan(
            clickableSpan,
            7,
            18,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        binding.tvTip.text = spannableString
        binding.tvTip.highlightColor = Color.TRANSPARENT
        binding.tvTip.movementMethod = LinkMovementMethod.getInstance()
    }
}
