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.util.Log
import android.view.View
import android.widget.Toast
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.databinding.ActivityRegisterBinding
import com.kaixed.kchat.utils.DensityUtil.dpToPx
import com.kaixed.kchat.utils.DrawableUtil.createDrawable
import com.kaixed.kchat.viewmodel.UserViewModel

class RegisterActivity : BaseActivity() {

    private lateinit var binding: ActivityRegisterBinding

    private var tvContinueEnable: Boolean = false

    private val mViewModel: UserViewModel by viewModels()

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

        initView()

        setOnClickListener()
    }

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

        binding.tvContinue.setOnClickListener {
            if (tvContinueEnable) {
                val username = binding.etUsername.text.toString().trim()
                val nickname = binding.etNickname.text.toString().trim()
                val password = binding.etPassword.text.toString().trim()
                val avatarUrl = ""
                val signature = ""

                mViewModel.register(username, nickname, password, avatarUrl, signature)
                    .observe(this) { registerResult ->
                        Log.d("haha", registerResult.toString())
                        when (registerResult?.code) {
                            "A0111" -> {
                                Toast.makeText(this, "用户名已存在，请重新注册", Toast.LENGTH_SHORT)
                                    .show()
                            }

                            "200" -> {
                                Toast.makeText(
                                    this,
                                    "注册成功，请前往登录界面登录",
                                    Toast.LENGTH_SHORT
                                )
                                    .show()
                                startActivity(Intent(this, LoginActivity::class.java))
                                finish()

                            }

                            else -> {
                                Toast.makeText(
                                    this,
                                    "系统服务器异常",
                                    Toast.LENGTH_SHORT
                                )
                                    .show()
                            }
                        }
                    }
            }
        }
    }

    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@RegisterActivity, 8)
        )
    }

    private fun setupTip() {
        val clickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                Toast.makeText(widget.context, "暂未编写", Toast.LENGTH_SHORT).show()
            }

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