package com.abbidot.tracker.ui.activity.account

import android.content.Intent
import android.text.InputType
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityCreateAccountBinding
import com.abbidot.tracker.ui.common.CountryCommon
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.UserProfileViewModel


class CreateAccountActivity :
    BaseActivity<ActivityCreateAccountBinding>(ActivityCreateAccountBinding::inflate) {

    private val mUserViewModel: UserProfileViewModel by viewModels()

    private lateinit var mCountryCommon: CountryCommon

    private var isShowPassword = false

    override fun getTopBar() = mViewBinding.createAccountTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")

        mViewBinding.apply {
            root.setBackgroundResource(R.color.white)
            ilCreateAccountFullName.let {
                it.tvInputNameTitle.text = getString(R.string.register_txt_name)
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext, it.rlEtInputLayout, tvFullNameErrorTip, it.etInputContent
                )
            }
            ilCreateAccountCountry.let {
                it.tvInputNameTitle.text = getString(R.string.txt_country)
                ViewUtil.instance.setEditTextDropSelectState(it.etInputContent)
                it.ivInputRepresentImage.visibility = View.VISIBLE
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext, it.rlEtInputLayout, tvSelectCountryErrorTip, it.etInputContent
                )
            }
            ilCreateAccountEmailAddress.let {
                it.tvInputNameTitle.text = getString(R.string.txt_email_address)
                it.etInputContent.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext, it.rlEtInputLayout, tvEmailErrorTip, it.etInputContent
                )
            }
            ilCreateAccountPassword.let {
                it.tvInputNameTitle.text = getString(R.string.login_txt_password)
                ViewUtil.instance.setShowAndHidePassword(
                    it.etInputContent, it.ivInputRepresentImage
                )
                it.etInputContent.addTextChangedListener { str ->
                    it.rlEtInputLayout.background = ContextCompat.getDrawable(
                        mContext, R.drawable.shape8_gray_border_white_bg
                    )
                    tvPasswordErrorTip.setTextColor(
                        ContextCompat.getColor(
                            mContext, R.color.blue_color1
                        )
                    )
                    str?.apply {
                        if (length >= 6) {
                            tvPasswordErrorTip.setCompoundDrawablesWithIntrinsicBounds(
                                R.drawable.icon_input_check_svg, 0, 0, 0
                            )
                        } else {
                            tvPasswordErrorTip.setCompoundDrawablesWithIntrinsicBounds(
                                0, 0, 0, 0
                            )
                        }
                    }
                }
            }

//            setSpannableClick(
//                ilPolicyTermsCheck.tvLoginAgreePrivacyContent,
//                getString(R.string.txt_create_account_terms1),
//                getString(R.string.txt_create_account_terms2)
//            )

            mCountryCommon =
                CountryCommon(mContext, object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        ilCreateAccountCountry.etInputContent.setText(mCountryCommon.getCountry())
                    }
                })

            setOnClickListenerViews(
                ilCreateAccountCountry.rlEtInputLayout,
                ilCreateAccountCountry.ivInputRepresentImage,
                ilCreateAccountPassword.ivInputRepresentImage,
                btnCreateAccountSignup
            )
        }

        mUserViewModel.getCountryCodes(this)
    }

    private fun setSpannableClick(textView: TextView, str1: String, str2: String) {
        textView.apply {
            val span1 = SpannableString(str1)
            span1.setSpan(object : ClickableSpan() {
                override fun onClick(v: View) {
                    ViewUtil.instance.goServiceContract(mActivity)
                }
            }, 40, 59, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

            val span2 = SpannableString(str2)
            span2.setSpan(object : ClickableSpan() {
                override fun onClick(v: View) {
                    ViewUtil.instance.goPrivacyPolicy(mActivity)
                }
            }, 0, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

            val spannableStringBuilder = SpannableStringBuilder()
            spannableStringBuilder.append(span1)
            spannableStringBuilder.append(" ")
            spannableStringBuilder.append(span2)
            text = spannableStringBuilder
            movementMethod = LinkMovementMethod.getInstance()
        }
    }

    override fun liveDataObserve() {
        mUserViewModel.apply {
            mCountryCodeLiveData.observe(this@CreateAccountActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mCountryCommon.setCountryCodeData(this)
                        }
                    }
                })
            }
            mRegisterV2LiveData.observe(this@CreateAccountActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            Util.dealLoginSuccessData(mContext, this)
                            val intent = Intent(mContext, SignupSuccessActivity::class.java)
                            startActivityFinish(intent)
                        }
                    }
                })
            }
        }
    }

    private fun signupClick() {
        mViewBinding.apply {
            val name = ilCreateAccountFullName.etInputContent.text.toString()
            val country = ilCreateAccountCountry.etInputContent.text.toString()
            val email = ilCreateAccountEmailAddress.etInputContent.text.toString()
            var password = ilCreateAccountPassword.etInputContent.text.toString()
            var isSure = true
            if (TextUtils.isEmpty(name)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilCreateAccountFullName.rlEtInputLayout, tvFullNameErrorTip
                )
            }
            if (TextUtils.isEmpty(country)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilCreateAccountCountry.rlEtInputLayout, tvSelectCountryErrorTip
                )
            }
            if (TextUtils.isEmpty(email) || !Utils.isValidEmail(email)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilCreateAccountEmailAddress.rlEtInputLayout, tvEmailErrorTip
                )
            }
            if (TextUtils.isEmpty(password) || password.length < 6) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilCreateAccountPassword.rlEtInputLayout, tvPasswordErrorTip
                )
            }
            if (!isSure) return

            if (!ilPolicyTermsCheck.cbLoginAgreePrivacyCheckbox.isChecked) {
                showToast(R.string.register_txt_agree,gravity = Gravity.CENTER)
                return
            }

            password = Utils.get32Md5Value(password)
            mUserViewModel.registerV2(
                this@CreateAccountActivity, email, password, name, mCountryCommon.getCountryCode()
            )
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ilCreateAccountCountry.rlEtInputLayout, ilCreateAccountCountry.ivInputRepresentImage -> mCountryCommon.showCountryCodeDialog()

                ilCreateAccountPassword.ivInputRepresentImage -> {
                    isShowPassword = !isShowPassword
                    ViewUtil.instance.showAndHidePasswordClick(
                        ilCreateAccountPassword.etInputContent,
                        ilCreateAccountPassword.ivInputRepresentImage,
                        isShowPassword
                    )
                }

                btnCreateAccountSignup -> signupClick()
            }
        }
    }
}