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

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.login.activity.LoginActivity
import com.seatel.mobilehall.ui.login.activity.TermsAndConditionsActivity
import com.seatel.mobilehall.ui.login.interactor.LoginInteractor
import com.seatel.mobilehall.ui.login.interactor.SignUpInteractor
import com.seatel.mobilehall.ui.login.model.ResetPasswordModel
import com.seatel.mobilehall.ui.login.presenter.LoginPresenter
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.facebook.login.LoginManager
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.fragment_signup.*
import kotlinx.android.synthetic.main.term_service_privacy_policy.*

class SignUpFragment : MainFragment(), SignUpInteractor.View, LoginInteractor.View {

    private val PHONE_NUMBER_REQUEST: Int = 100
    private var userId = ""
    private var mLoginPresenter: LoginPresenter? = null
    private var mSignUpPresenter: ResetPasswordPresenter? = null
    private var mUserId = ""
    private lateinit var mSocialType: String
    private var isRegisterSocail = false
    private var typeSignUp = Constant.REGISTER


    override fun onLoginSucceed(isNoneSeatel: Boolean, isPostPad: Boolean) {
    }

    override fun onLoginFailed(error: VolleyError) {
    }

    override fun onLoginWithSocialSucceed(uId: String) {
        LoginManager.getInstance().logOut()
        mLoginPresenter?.onLoginWithSocial(uId)
        userId = uId
    }

    override fun onLoginWithSocialFail(error: String) {
        SeatelUtils.showErrorDialog(getmContext(), error)
        error_view.visibility = View.GONE
    }

    override fun onAccountExist(
        isExist: Boolean,
        phoneNum: String,
        isNoneSeatel: Boolean,
        isPostPad: Boolean
    ) {
        if (isExist) {
            SeatelSharePreferences.getInstance(getmContext())?.setPasswordLogin("")
            SeatelSharePreferences.getInstance(getmContext())?.setPhoneLogin(phoneNum)
            SeatelSharePreferences.getInstance(getmContext())?.setMainPhoneLogin(phoneNum)
            SeatelSharePreferences.getInstance(requireContext())?.setPhoneLogin("true")
            SeatelSharePreferences.getInstance(requireContext())?.setNoneSeatelNumber(isNoneSeatel)
            if (!isNoneSeatel)
                SeatelSharePreferences.getInstance(requireContext())?.setIsPostPaid(isPostPad)
            SeatelUtils.gotoMainScreen(context)
            getMainActivity().closeHome()
        } else {
            val signUp = SignUpFragment()
            // signUp.setData(userId, mSManager.socialType)
            getmMainFragmentPresenter()!!.addFragment(signUp, true)
        }
        error_view.visibility = View.GONE
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PHONE_NUMBER_REQUEST) {
            } else {
                //   mSManager.onActivityResultCallBack(requestCode, resultCode, data)
            }
        }
    }

    fun setData(id: String) {
        mUserId = id
        //  mSocialType = socailType
    }

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

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mLoginPresenter = LoginPresenter(getmContext(), this)

        if (!TextUtils.isEmpty(mUserId)) {
            isRegisterSocail = true
            ctv_email.visibility = View.GONE
            view_socail_login.visibility = View.GONE
            typeSignUp = Constant.SOCIAL_REGISTER
        }
        ctv_phone_number.hint = ctv_phone_number.hint
        ctv_email.hint = ctv_email.hint
        ctv_password.hint = ctv_password.hint
        ctv_confirm_password.hint = ctv_confirm_password.hint

        term_of_service.setOnClickListener {
            TermsAndConditionsActivity.launch(getmContext())
        }

        text_view_login.setOnClickListener {
            getmMainFragmentPresenter()!!.addFragment(
                LoginFragment(),
                true
            )
        }
        image_view_back.setOnClickListener {
            onBackPress()
            SeatelUtils.hideKeyboard(getmContext() as LoginActivity)
        }
        mSignUpPresenter = ResetPasswordPresenter(getmContext(), this)

        button_yes.setOnClickListener {
            if (checkValidate()) {
                error_view.setViewMode(ErrorHandleView.Mode.LOADING)
                mSignUpPresenter?.onRequestCode(
                    ctv_phone_number.text?.trim().toString(),
                    ctv_email.text?.trim().toString(),
                    typeSignUp,
                    "v2/",
                    ""
                )
            }
        }
        // mSManager = SFacebook(getmContext(), this)

        image_view_fb.setOnClickListener {
            //   mSManager = mSManager.getSocial(SManager.SocialType.FACEBOOK) as SFacebook
            //  mSManager.onLogin()
        }
        image_view_we_chat.setOnClickListener {
            //  mSManager = mSManager.getSocial(SManager.SocialType.WE_CHAT) as SWeChat
            // mSManager.onLogin()
        }
        image_view_instagram.setOnClickListener {
            //  mSManager = mSManager.getSocial(SManager.SocialType.INSTAGRAM) as SInstagram
            // mSManager.onLogin()
        }
        /*image_view_link_in.setOnClickListener {
            mSManager = mSManager.getSocial(SManager.SocialType.LINKED_IN) as SLinkedIn
            mSManager.onLogin()
        }*/
    }


    override fun onRequestCodeSucceed(resetPasswordModel: ResetPasswordModel) {
        error_view.visibility = View.GONE
        val confirmationFragment = ConfirmationFragment()
        if (isRegisterSocail)
            confirmationFragment.setDataPost(
                ctv_phone_number.text.toString(),
                mUserId,
                ctv_password.text.toString(),
                mSocialType,
                Constant.SOCIAL_REGISTER
            )
        else
            confirmationFragment.setDataPost(
                ctv_phone_number.text.toString(),
                ctv_email.text.toString(),
                ctv_password.text.toString(),
                "",
                Constant.REGISTER
            )
        getmMainFragmentPresenter()!!.addFragment(confirmationFragment, true)
        SeatelUtils.hideKeyboard(getmContext() as LoginActivity)
    }

    override fun onRequestCodeFailed(error: VolleyError) {
        if (error_view != null) {
            error_view.visibility = View.GONE
            SeatelAlertDialog.with(getmContext(), SeatelSuperRequest.getErrorMessageFrom(error))
                .show()
        }
    }

    override fun onBackPress() {
        super.onBackPress()
        getmMainFragmentPresenter()!!.addFragment(LoginFragment(), true)
        if (mUserId.isNotEmpty()) {
            LoginManager.getInstance().logOut()
        }
    }

    private fun checkValidate(): Boolean {
        val phoneNum = ctv_phone_number.text?.trim()
        val email = ctv_email.text?.trim().toString()
        val password = ctv_password.text?.trim()
        val confirmPassword = ctv_confirm_password.text?.trim()

        var msg = ""

        if (phoneNum!!.isEmpty()) {
            msg = getString(R.string.phone_empty)
            ctv_phone_number.requestFocus()
        } else if (phoneNum.startsWith("0") && phoneNum.length < 9 ||
            phoneNum.startsWith("85") && phoneNum.length < 11 || phoneNum.length < 8
        ) {

            msg = getString(R.string.incorrect_phone_num)
            ctv_phone_number.requestFocus()
        } else if (!TextUtils.isEmpty(email) && SeatelUtils.isEmailValid(email)) {
            msg = getString(R.string.incorrect_phone_email)
            ctv_email.requestFocus()
        } else if (password!!.isEmpty()) {
            msg = getString(R.string.password_empty)
            ctv_password.requestFocus()
        } else if (confirmPassword!!.isEmpty()) {
            msg = getString(R.string.confirm_password_empty)
            ctv_confirm_password.requestFocus()
        } else if (!TextUtils.equals(password, confirmPassword)) {
            msg = getString(R.string.confirm_password_not_match)
        } else if (password.length < 6) {
            msg = getString(R.string.password_at_least_6_digit)
            ctv_password.requestFocus()
        }

        if (!TextUtils.isEmpty(msg)) {
            SeatelAlertDialog.with(requireContext(), msg).show()
            return false
        }
        return true
    }
}

