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

import android.content.Context
import android.graphics.Paint
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.View.OnClickListener
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentBaseEmailValidBinding
import com.abbidot.tracker.vm.CountDownTimerViewModel
import com.abbidot.tracker.vm.UserProfileViewModel
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo


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

    private val mCountDownTimerViewModel: CountDownTimerViewModel by viewModels()
    private val mRegisterViewModel: UserProfileViewModel by viewModels()

    private val mResendCodeTime = 5 * 60
    private var mEmail = ""
    private var mBtnString = ""
    private var mEmailCodeType = 0

    private lateinit var mOnOkClickListener: OnClickListener

    companion object {
        @JvmStatic
        fun newInstance(
            context: Context,
            emailCodeType: Int,
            btnString: String = "",
            okClickListener: OnClickListener
        ) = EmailValidFragment().apply {
            mContext = context
            mBtnString = btnString
            mEmailCodeType = emailCodeType
            mOnOkClickListener = okClickListener
        }
    }

    fun setEmail(email: String) {
        mEmail = email
        //返回上一个页面修改邮箱，再次回到需要更新邮箱显示
        if (isResumed) {
            mViewBinding.vetForgotPasswordV2EditText.clearContent()
            mCountDownTimerViewModel.stopCountDown()
            setResendCodeBtnEnabled(false)
            mCountDownTimerViewModel.startCountDown(mResendCodeTime.toLong())
            formatEmail()
        }
    }

    override fun initData() {
        super.initData()

        formatEmail()

        mViewBinding.apply {

            if (!TextUtils.isEmpty(mBtnString)) {
                btnForgotPasswordV2TwoContinue.text = mBtnString
            }

            //添加下划线
            tvForgotPasswordResendCodeBtn.paintFlags = Paint.UNDERLINE_TEXT_FLAG

            vetForgotPasswordV2EditText.setEditClickListener {
                vetForgotPasswordV2EditText.setBoxBackground(
                    ContextCompat.getDrawable(
                        mContext!!, R.drawable.shape8_gray_border_white_bg
                    )
                )
            }
            setOnClickListenerViews(btnForgotPasswordV2TwoContinue, tvForgotPasswordResendCodeBtn)
        }

        mCountDownTimerViewModel.startCountDown(mResendCodeTime.toLong())
    }

    private fun formatEmail() {
        val emailString = String.format(
            getString(R.string.txt_otp_verification_tips), mEmail
        )
        //找出邮箱并加上下划线
//        val index = 38
//        val spannableString = SpannableString(emailString)
//        spannableString.setSpan(
//            UnderlineSpan(), index, index + mEmail.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
//        )
        mViewBinding.tvForgotPasswordV2EmailDec.text = emailString
    }

    override fun liveDataObserve() {
        mCountDownTimerViewModel.apply {
            mCountDowningLiveData.observe(viewLifecycleOwner) {
//                val t = it / 60f
//                val str = if (t > 0 && t < 1) 1
//                else if (t >= 1) t.toInt()
//                else 0
                mViewBinding.tvForgotPasswordV2TwoValidMin.let { v ->
                    v.text = String.format(getString(R.string.txt_code_valid_min), "$it")
                    v.visibility = if (it == 0L) View.INVISIBLE else View.VISIBLE
                }
            }

            mCountDownEndLiveData.observe(viewLifecycleOwner) {
                mViewBinding.tvForgotPasswordV2CountdownTime.visibility = View.GONE
                mViewBinding.tvForgotPasswordV2TimeRemaining.visibility = View.GONE
                mViewBinding.tvForgotPasswordV2TimeSec.visibility = View.GONE
                setResendCodeBtnEnabled(true)
            }
        }

        mRegisterViewModel.apply {
            mGetEmailCodeLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            showToast(R.string.txt_code_success, gravity = Gravity.CENTER)
//                            mViewBinding.tvForgotPasswordV2CountdownTime.visibility = View.VISIBLE
//                            mViewBinding.tvForgotPasswordV2TimeRemaining.visibility = View.VISIBLE
//                            mViewBinding.tvForgotPasswordV2TimeSec.visibility = View.VISIBLE
                            mCountDownTimerViewModel.startCountDown(mResendCodeTime.toLong())
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        setResendCodeBtnEnabled(true)
                    }
                })
            }

            mValidateCodeLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mOnOkClickListener.onClick(view)
                        }
                    }
                })
            }
        }
    }

    private fun setResendCodeBtnEnabled(enabled: Boolean) {
        mViewBinding.tvForgotPasswordResendCodeBtn.apply {
            isEnabled = enabled
            if (enabled) {
                setTextColor(
                    ContextCompat.getColor(
                        mContext!!, R.color.black
                    )
                )
            } else {
                setTextColor(
                    ContextCompat.getColor(
                        mContext!!, R.color.gray_color8
                    )
                )
            }
        }
    }

    private fun continueVerifyCode() {
        mViewBinding.vetForgotPasswordV2EditText.apply {
            if (TextUtils.isEmpty(content) || content.length < 4) {
                YoYo.with(Techniques.Shake).onStart {
                    setBoxBackground(
                        ContextCompat.getDrawable(
                            mContext!!, R.drawable.shape8_red_border_white_bg
                        )
                    )
                }.duration(50).playOn(this)
                return
            }

            mRegisterViewModel.validateCode(
                this@EmailValidFragment, mEmail, content, mEmailCodeType
            )
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnForgotPasswordV2TwoContinue -> continueVerifyCode()

                tvForgotPasswordResendCodeBtn -> {
                    setResendCodeBtnEnabled(false)
                    mRegisterViewModel.getEmailCode(
                        activity as BaseActivity<*>, mEmail, mEmailCodeType
                    )
                }
            }
        }
    }
}