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.ui.login.activity.LoginActivity
import com.seatel.mobilehall.ui.login.interactor.SignUpInteractor
import com.seatel.mobilehall.ui.login.model.ResetPasswordModel
import com.seatel.mobilehall.ui.login.presenter.ResetPasswordPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.CustomKeyboard
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_change_password.button_yes
import kotlinx.android.synthetic.main.activity_change_password.image_view_close
import kotlinx.android.synthetic.main.fragment_forget_password.error_view
import kotlinx.android.synthetic.main.fragment_forget_password.layout_main
import kotlinx.android.synthetic.main.fragment_forget_password.text_view_login
import kotlinx.android.synthetic.main.fragment_login.edit_text_phone_number

class ForgotPasswordFragment : MainFragment(), SignUpInteractor.View {


    private val OFFSET = 50
    private var phoneNumber = ""
    private lateinit var mSignUpPresenter: ResetPasswordPresenter
    private var mMainPhoneNumber = ""
    private var typeForgotPassword = Constant.RESET_PASSWORD
    private var isRequestCode = false

    private var keyboardView: CustomKeyboard? = null

    fun setDataForAddNewPhone(mainPhone: String) {
        this.mMainPhoneNumber = mainPhone
        typeForgotPassword = Constant.LINK_PHONE_NUMBER
    }

    fun setDataForModifyProfile(typeConfirm: String) {
        typeForgotPassword = typeConfirm
    }

    private fun showNextScreen() {
        val confirmationFragment = ConfirmationForgotPassFragment()
        if (mMainPhoneNumber.isNotEmpty())
            confirmationFragment.setDataForAddPhoneNumber(mMainPhoneNumber)
        confirmationFragment.setDataPost(phoneNumber, "", "", "", typeForgotPassword)
        getmMainFragmentPresenter()!!.addFragment(confirmationFragment, true)
        SeatelUtils.hideKeyboard(getMainActivity())
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setActivity(context as LoginActivity)
        setFragmentLayout(R.layout.fragment_forget_password)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        keyboardView = view.findViewById(R.id.keyboard_View)
        init()
    }

    private fun init() {

        if (typeForgotPassword.equals(Constant.VERRIFY_PHONE_NUMBER, true))
            text_view_login.text = getString(R.string.update_profile)
        if (mMainPhoneNumber.isNotEmpty())
            text_view_login.text = getString(R.string.add_phone_number)

        mSignUpPresenter = ResetPasswordPresenter(requireContext(), this)

        image_view_close.setOnClickListener { onBackPress() }

        button_yes.isEnabled = true
        button_yes.setOnClickListener {

            if (keyboardView != null)
                keyboardView?.hideKeyBoard()
            startPostRequest()
        }


        edit_text_phone_number.hint = edit_text_phone_number.hint
        layout_main.setOnClickListener {
            if (keyboardView != null) {
                SeatelUtils.hideKeyboard(context as LoginActivity)
                keyboardView?.hideKeyBoard()
            }
        }

        edit_text_phone_number.showSoftInputOnFocus = false

        edit_text_phone_number.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                SeatelUtils.hideKeyboard(getMainActivity())
                edit_text_phone_number.requestFocus()
                keyboardView?.setmMaxLenght(15)
                keyboardView?.showKeyBoard(v as EditText)
            }
            false
        }
    }

    override fun onBackPress() {
        if (isKeyboardHided())
            when {
                typeForgotPassword.equals(Constant.VERRIFY_PHONE_NUMBER, true) -> {
                    getMainActivity().finish()
                    return
                }
                mMainPhoneNumber.isEmpty() -> {
                    getmMainFragmentPresenter()!!.addFragment(LoginFragment(), true)
                    return
                }
                else -> getMainActivity().finish()
            }
        else hideKeyBoard()
    }

    override fun onRequestCodeSucceed(resetPassword: ResetPasswordModel) {
        if (resetPassword.message == "OK") {
            button_yes.isEnabled = false

            if (error_view == null) return
            error_view.visibility = View.GONE
            showNextScreen()
            isRequestCode = false
        }
    }

    override fun onRequestCodeFailed(error: VolleyError) {
        if (error_view == null) return
        error_view.visibility = View.GONE
        SeatelUtils.showErrorDialog(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error))
        isRequestCode = false
    }

    private fun startPostRequest() {
        if (isRequestCode) return
        phoneNumber = edit_text_phone_number.text!!.trim().toString()

        if (TextUtils.isEmpty(phoneNumber)) {
            SeatelAlertDialog.with(requireContext(), getString(R.string.phone_empty)).show()
            return

        } else if (phoneNumber.startsWith("0") && phoneNumber.length < 9 ||
            phoneNumber.startsWith("85") && phoneNumber.length < 11 || phoneNumber.length < 8
        ) {

            SeatelAlertDialog.with(requireContext(), getString(R.string.incorrect_phone_num)).show()
            return
        }
//        getHomeActivity().setFilterSMS(SeatelUtils.checkIsNonSeatel(phoneNumber))
        isRequestCode = true
        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        if (mMainPhoneNumber.isEmpty())
            mSignUpPresenter.onRequestCode(phoneNumber, "", typeForgotPassword, "v2/", "")
        else
            mSignUpPresenter.onRequestCode(
                mMainPhoneNumber,
                "",
                typeForgotPassword,
                "v2/",
                phoneNumber
            )
    }

    override fun onDestroy() {
        super.onDestroy()
        mSignUpPresenter.onDestroy()
    }

    override fun getFragmentOffset(): Int {
        return OFFSET
    }

    override fun isKeyboardHided(): Boolean {
        return keyboardView?.visibility == View.GONE
    }

    override fun hideKeyBoard() {
        super.hideKeyBoard()
        keyboardView?.hideKeyBoard()
    }
}