package com.abbidot.tracker.ui.fragment.account

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentCreateAccountV2ThreeBinding
import com.abbidot.tracker.ui.activity.account.CreateAccountV2Activity
import com.abbidot.tracker.ui.activity.account.SignupSuccessActivity
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


/**
 * A simple [Fragment] subclass.
 * Use the [CreateAccountV2ThreeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class CreateAccountV2ThreeFragment : BaseFragment<FragmentCreateAccountV2ThreeBinding>(
    FragmentCreateAccountV2ThreeBinding::inflate
) {

    private val mUserViewModel: UserProfileViewModel by viewModels()

    private lateinit var mCreateAccountV2Activity: CreateAccountV2Activity

    private lateinit var mCountryCommon: CountryCommon

    private var isShowPassword = false

    companion object {
        @JvmStatic
        fun newInstance(context: Context) = CreateAccountV2ThreeFragment().apply {
            mContext = context
        }
    }

    override fun initData() {
        super.initData()
        mCreateAccountV2Activity = activity as CreateAccountV2Activity
        mViewBinding.apply {

            ilCreateAccountV2FullName.let {
                it.tvInputNameTitle.setText(R.string.register_txt_name)
                it.etInputContent.setHint(R.string.acccount_name)
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext!!,
                    it.rlEtInputLayout,
                    tvCreateAccountV2FullNameError,
                    it.etInputContent
                )
            }

            ilCreateAccountV2Country.let {
                it.tvInputNameTitle.setText(R.string.txt_country)
                ViewUtil.instance.setEditTextDropSelectState(it.etInputContent)
                it.ivInputRepresentImage.visibility = View.VISIBLE
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext!!,
                    it.rlEtInputLayout,
                    tvCreateAccountV2SelectCountryError,
                    it.etInputContent
                )
            }

            ilCreateAccountV2Password.let {
                it.tvInputNameTitle.setText(R.string.login_txt_password)
                it.etInputContent.setHint(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
                    )
                    tvCreateAccountV2PasswordError.setTextColor(
                        ContextCompat.getColor(
                            mContext!!, R.color.blue_color1
                        )
                    )
                    str?.apply {
                        if (length >= 6) {
                            tvCreateAccountV2PasswordError.setCompoundDrawablesWithIntrinsicBounds(
                                R.drawable.icon_input_check_svg, 0, 0, 0
                            )
                        } else {
                            tvCreateAccountV2PasswordError.setCompoundDrawablesWithIntrinsicBounds(
                                0, 0, 0, 0
                            )
                        }
                    }
                }
            }

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

            setOnClickListenerViews(
                ilCreateAccountV2Country.rlEtInputLayout,
                ilCreateAccountV2Country.ivInputRepresentImage,
                ilCreateAccountV2Password.ivInputRepresentImage,
                btnCreateAccountV2Signup
            )
        }

        mUserViewModel.getCountryCodes(mCreateAccountV2Activity)
    }

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

    private fun signupClick() {
        mViewBinding.apply {
            val name = ilCreateAccountV2FullName.etInputContent.text.toString()
//            val country = ilCreateAccountV2Country.etInputContent.text.toString()
            val country = "1212"
            val email = mCreateAccountV2Activity.mUserEmail
            var password = ilCreateAccountV2Password.etInputContent.text.toString()
            var isSure = true
            if (TextUtils.isEmpty(name)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext!!,
                    ilCreateAccountV2FullName.rlEtInputLayout,
                    tvCreateAccountV2FullNameError
                )
            }
            if (TextUtils.isEmpty(country)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext!!,
                    ilCreateAccountV2Country.rlEtInputLayout,
                    tvCreateAccountV2SelectCountryError
                )
            }
//            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!!,
                    ilCreateAccountV2Password.rlEtInputLayout,
                    tvCreateAccountV2PasswordError
                )
            }
            if (!isSure) return

//            if (!ilPolicyTermsCheck.cbLoginAgreePrivacyCheckbox.isChecked) {
//                showToast(R.string.register_txt_agree)
//                return
//            }

            password = Utils.get32Md5Value(password)
            mUserViewModel.registerV2(
                mCreateAccountV2Activity, email, password, name, mCountryCommon.getCountryCode()
            )
        }
    }

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

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

                btnCreateAccountV2Signup -> signupClick()
            }
        }
    }
}