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

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
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 com.seatel.mobilehall.databinding.FragmentForgetPasswordBinding
import com.seatel.mobilehall.databinding.FragmentSignupBinding
import com.seatel.mobilehall.util.viewFragmentBinding

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

    private val binding by viewFragmentBinding(
        FragmentForgetPasswordBinding::inflate
    )

    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 onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        keyboardView = binding.keyboardView // Set up the keyboard view
        init()
        return binding.root
    }

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

        // Initialize ViewBinding
      //  _binding = FragmentForgetPasswordBinding.bind(view)


    }

    private fun init() {
        if (typeForgotPassword.equals(Constant.VERRIFY_PHONE_NUMBER, true)) {
            binding.textViewLogin.text = getString(R.string.update_profile)
        }

        if (mMainPhoneNumber.isNotEmpty()) {
            binding.textViewLogin.text = getString(R.string.add_phone_number)
        }

        mSignUpPresenter = ResetPasswordPresenter(requireContext(), this)

        binding.imageViewClose.setOnClickListener { onBackPress() }

        binding.buttonYes.isEnabled = true
        binding.buttonYes.setOnClickListener {
            keyboardView?.hideKeyBoard()
            startPostRequest()
        }

        binding.editTextPhoneNumber.hint = binding.editTextPhoneNumber.hint
        binding.layoutMain.setOnClickListener {
            SeatelUtils.hideKeyboard(requireContext() as LoginActivity)
            keyboardView?.hideKeyBoard()
        }

        binding.editTextPhoneNumber.showSoftInputOnFocus = false

        binding.editTextPhoneNumber.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                SeatelUtils.hideKeyboard(requireContext() as LoginActivity)
                binding.editTextPhoneNumber.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") {
            binding.buttonYes.isEnabled = false

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

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

    private fun startPostRequest() {
        if (isRequestCode) return
        phoneNumber = binding.editTextPhoneNumber.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
        }

        isRequestCode = true
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)

        if (mMainPhoneNumber.isEmpty())
            mSignUpPresenter.onRequestCode(phoneNumber, "", typeForgotPassword, "v2/", "")
        else
            mSignUpPresenter.onRequestCode(
                mMainPhoneNumber,
                "",
                typeForgotPassword,
                "v2/",
                phoneNumber
            )
    }

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

    override fun getFragmentOffset(): Int {
        return OFFSET
    }

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

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