package com.seatel.mobilehall.ui.login.fragment

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.databinding.FragmentConfirmationForgotPassBinding
import com.seatel.mobilehall.ui.login.interactor.ForgotPasswrodVerifyCodeInteractor
import com.seatel.mobilehall.ui.login.interactor.SignUpInteractor
import com.seatel.mobilehall.ui.login.model.ResetPasswordModel
import com.seatel.mobilehall.ui.login.presenter.ConfirmSignUpPresenter
import com.seatel.mobilehall.ui.login.presenter.ForgotPasswrodVerifyCodePresenter
import com.seatel.mobilehall.ui.login.presenter.SignUpPresenter
import com.seatel.mobilehall.util.AnimationUtil
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView

class ConfirmationForgotPassFragment : ConfirmationFragment(), SignUpInteractor.View,
    ForgotPasswrodVerifyCodeInteractor.View, View.OnTouchListener {

    private lateinit var mConfirmUserPresenter: ForgotPasswrodVerifyCodePresenter
    private lateinit var mSignUpPresenter: SignUpPresenter
    private lateinit var mConfirmCodeAddNewPhonePresenter: ConfirmSignUpPresenter
    private var mConfirmCode = ""

    private var _binding: FragmentConfirmationForgotPassBinding? = null
    private val binding get() = _binding!!

    override fun onRequestCodeSucceed(resetPassword: ResetPasswordModel) {
        binding.errorView.visibility = View.GONE
        startResendCountDown()
        binding.tvResendCodeConfirm.isEnabled = true
    }

    override fun onRequestCodeFailed(error: VolleyError) {
        isRequesting = false
        binding.errorView.visibility = View.GONE
        SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error))
            .show()
        binding.tvResendCodeConfirm.isEnabled = true
    }

    override fun onVerifyCodeSucceed() {
        isRequesting = false
        cancelRuningTimer()
        if (isFeatureAddNewPhone()) {
            getMainActivity().closeHome()
        } else {
            val newPassFragment = NewPasswordFragment()
            if (TextUtils.isEmpty(mConfirmCode)) {
                mConfirmCode = binding.textViewHidden.text.toString().trim()
                binding.keyboardView.hideKeyBoard()
            }
            newPassFragment.setDataPost(getPhone(), mConfirmCode)
            getmMainFragmentPresenter()!!.addFragment(newPassFragment, true)
        }
        binding.buttonConfirm.isEnabled = true
    }

    override fun onVerifyCodeFailed(error: VolleyError) {
        isRequesting = false
        binding.errorView.visibility = View.GONE
        SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error))
            .show()
        mConfirmCode = ""
        binding.buttonConfirm.isEnabled = true
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_confirmation_forgot_pass)
    }

    private fun startConfirmCode() {
        if (isRequesting) return
        var codeConfirm = ""
        if (binding.textViewHidden != null) {
            codeConfirm = binding.textViewHidden.text.toString().trim()
        }
        if (TextUtils.isEmpty(codeConfirm) || codeConfirm.length < 6) {
            SeatelAlertDialog.with(requireContext(), getString(R.string.enter_confirmation)).show()
            return
        }
        isRequesting = true
        binding.buttonConfirm.isEnabled = false
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)

        when {
            getTypeConfirm().equals(Constant.VERRIFY_PHONE_NUMBER, true) -> {
                mConfirmCodeAddNewPhonePresenter.onConfirmCode(
                    "v2/", codeConfirm, "", "", getPhone(), "", "", getTypeConfirm()
                )
                return
            }

            isFeatureAddNewPhone() -> {
                mConfirmCodeAddNewPhonePresenter.onConfirmCode(
                    "v2/",
                    codeConfirm,
                    "",
                    getPhone(),
                    getMainPhone(),
                    "",
                    "",
                    Constant.LINK_PHONE_NUMBER
                )
                return
            }

            else -> {
                mConfirmUserPresenter.onVerifyCode(codeConfirm, getPhone())
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mConfirmCodeAddNewPhonePresenter.onDestroy()
        mConfirmUserPresenter.onDestroy()
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        v?.let {
            when (it.id) {
                R.id.edit_text_confirm_code_one, R.id.edit_text_confirm_code_two, R.id.edit_text_confirm_code_three,
                R.id.edit_text_confirm_code_four, R.id.edit_text_confirm_code_five, R.id.edit_text_confirm_code_six -> {
                    onEditTextSearchTouch()
                }
            }
        }
        return false
    }

    private fun setEditTextTouchListener(textEdit: EditText) {
        textEdit.setOnTouchListener(this)
        textEdit.showSoftInputOnFocus = false
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentConfirmationForgotPassBinding.bind(view)

        mConfirmCodeAddNewPhonePresenter = ConfirmSignUpPresenter(requireContext(), this)
        mConfirmUserPresenter = ForgotPasswrodVerifyCodePresenter(requireContext(), this)
        mSignUpPresenter = SignUpPresenter(requireContext(), this)

        setEditTextTouchListener(binding.editTextConfirmCodeOne)
        setEditTextTouchListener(binding.editTextConfirmCodeTwo)
        setEditTextTouchListener(binding.editTextConfirmCodeThree)
        setEditTextTouchListener(binding.editTextConfirmCodeFour)
        setEditTextTouchListener(binding.editTextConfirmCodeFive)
        setEditTextTouchListener(binding.editTextConfirmCodeSix)

        binding.viewInputCode.setOnClickListener {
            onEditTextSearchTouch()
        }

        binding.buttonConfirm.setOnClickListener {
            AnimationUtil.instance?.collapse(binding.layoutKeyboard)
            startConfirmCode()
        }

        binding.tvResendCodeConfirm.setOnClickListener {
            binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
            binding.tvResendCodeConfirm.isEnabled = false
            resetCodeInput()
            onEditTextSearchTouch()
            when {
                getTypeConfirm().equals(Constant.VERRIFY_PHONE_NUMBER, true) -> {
                    mSignUpPresenter.onRequestCode(getPhone(), "", getTypeConfirm(), "v2/", "")
                    return@setOnClickListener
                }

                isFeatureAddNewPhone() -> {
                    mSignUpPresenter.onRequestCode(
                        getMainPhone(),
                        "",
                        getTypeConfirm(),
                        "v2/",
                        getPhone()
                    )
                    return@setOnClickListener
                }

                else -> mSignUpPresenter.onRequestCode(getPhone(), "", getTypeConfirm(), "v2/", "")
            }
        }

        binding.imageViewBack.setOnClickListener { onBackPress() }
    }

    private fun onEditTextSearchTouch() {
        AnimationUtil.instance?.expand(binding.layoutKeyboard)
    }

    override fun onBackPress() {
        cancelRuningTimer()
        val forgotPass = ForgotPasswordFragment()
        if (getTypeConfirm().equals(Constant.VERRIFY_PHONE_NUMBER, true)) {
            forgotPass.setDataForModifyProfile(Constant.VERRIFY_PHONE_NUMBER)
        } else if (isFeatureAddNewPhone()) {
            forgotPass.setDataForAddNewPhone(getMainPhone())
        }
        getmMainFragmentPresenter()!!.addFragment(forgotPass, true)
    }

    override fun code(code: String) {
        mConfirmCode = code
        super.code(code)
    }
}
