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.fragment.app.Fragment
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 com.seatel.mobilehall.databinding.FragmentSignupBinding

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
    private lateinit var binding: FragmentSignupBinding  // ViewBinding for this fragment

    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)
        binding.errorView.visibility = View.GONE
    }

    override fun onAccountExist(isExist: Boolean, phoneNum: String, isNoneSeatel: Boolean, isPostPad: Boolean) {
        if (isExist) {
            SeatelSharePreferences.getInstance(getmContext())?.apply {
                setPasswordLogin("")
                setPhoneLogin(phoneNum)
                setMainPhoneLogin(phoneNum)
                setPhoneLogin("true")
                setNoneSeatelNumber(isNoneSeatel)
                if (!isNoneSeatel) setIsPostPaid(isPostPad)
            }
            SeatelUtils.gotoMainScreen(context)
            getMainActivity().closeHome()
        } else {
            val signUp = SignUpFragment()
            getmMainFragmentPresenter()!!.addFragment(signUp, true)
        }
        binding.errorView.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) {
            }
        }
    }

    fun setData(id: String) {
        mUserId = id
    }

    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)

        binding = FragmentSignupBinding.bind(view)  // Initialize ViewBinding

        mLoginPresenter = LoginPresenter(getmContext(), this)

        if (!TextUtils.isEmpty(mUserId)) {
            isRegisterSocail = true
            binding.ctvEmail.visibility = View.GONE
            binding.viewSocailLogin.visibility = View.GONE
            typeSignUp = Constant.SOCIAL_REGISTER
        }

        // Setting hints using ViewBinding
        binding.ctvPhoneNumber.hint = binding.ctvPhoneNumber.hint
        binding.ctvEmail.hint = binding.ctvEmail.hint
        binding.ctvPassword.hint = binding.ctvPassword.hint
        binding.ctvConfirmPassword.hint = binding.ctvConfirmPassword.hint
       /* binding.termOfService.setOnClickListener {
            TermsAndConditionsActivity.launch(getmContext())
        }*/

        binding.textViewLogin.setOnClickListener {
            getmMainFragmentPresenter()!!.addFragment(LoginFragment(), true)
        }

        binding.imageViewBack.setOnClickListener {
            onBackPress()
            SeatelUtils.hideKeyboard(getmContext() as LoginActivity)
        }

        mSignUpPresenter = ResetPasswordPresenter(getmContext(), this)

        binding.buttonYes.setOnClickListener {
            if (checkValidate()) {
                binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
                mSignUpPresenter?.onRequestCode(
                    binding.ctvPhoneNumber.text?.trim().toString(),
                    binding.ctvEmail.text?.trim().toString(),
                    typeSignUp,
                    "v2/",
                    ""
                )
            }
        }

        binding.imageViewFb.setOnClickListener {
            // Handle Facebook login
        }

        binding.imageViewWeChat.setOnClickListener {
            // Handle WeChat login
        }

        binding.imageViewInstagram.setOnClickListener {
            // Handle Instagram login
        }
    }

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

    override fun onRequestCodeFailed(error: VolleyError) {
        binding.errorView.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 = binding.ctvPhoneNumber.text?.trim()
        val email = binding.ctvEmail.text?.trim().toString()
        val password = binding.ctvPassword.text?.trim()
        val confirmPassword = binding.ctvConfirmPassword.text?.trim()

        var msg = ""

        if (phoneNum!!.isEmpty()) {
            msg = getString(R.string.phone_empty)
            binding.ctvPhoneNumber.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)
            binding.ctvPhoneNumber.requestFocus()
        } else if (!TextUtils.isEmpty(email) && SeatelUtils.isEmailValid(email)) {
            msg = getString(R.string.incorrect_phone_email)
            binding.ctvEmail.requestFocus()
        } else if (password!!.isEmpty()) {
            msg = getString(R.string.password_empty)
            binding.ctvPassword.requestFocus()
        } else if (confirmPassword!!.isEmpty()) {
            msg = getString(R.string.confirm_password_empty)
            binding.ctvConfirmPassword.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)
            binding.ctvPassword.requestFocus()
        }

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