package com.seatel.mobilehall.ui.home.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 android.widget.LinearLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.android.volley.Request
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.databinding.FragmentPinlessBinding
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.activity.PaymentActivity
import com.seatel.mobilehall.ui.home.adapter.TopupWithPlanAdapter
import com.seatel.mobilehall.ui.home.interactor.TopUpWithPlanInteractor
import com.seatel.mobilehall.ui.home.model.TopUpWithPlanModel
import com.seatel.mobilehall.ui.home.presenter.TopUpWithPlanPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.FirebaseAnalyticsUtil
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import org.json.JSONException
import org.json.JSONObject


class PinlessFragment : BaseFragment(), TopUpWithPlanInteractor.View {

    private val TAG = PinlessFragment::class.java.simpleName

    private var _fragmentPinLessBinding: FragmentPinlessBinding? = null
    private val pinlessBinding get() = _fragmentPinLessBinding!!


    private var mView: View? = null
    private var mIsFocus: Boolean = true
    private var mPhone = ""
    private var mAutoSelect = false
    private var mClearSelect = true

    fun setPhoneNumber(phone: String) {
        this.mPhone = phone
    }

    override fun isKeyboardHided(): Boolean {
        if (pinlessBinding.keyboardViewTopUp != null)
            return pinlessBinding.keyboardViewTopUp.visibility == View.GONE
        return false
    }

    override fun hideKeyBoard() {
        super.hideKeyBoard()
        pinlessBinding.keyboardViewTopUp.hideKeyBoard()
        pinlessBinding.linearLayoutPinless.animate().translationY(0f).duration = 300
    }


    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)

    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _fragmentPinLessBinding = FragmentPinlessBinding.inflate(inflater, container, false)
        return pinlessBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        FirebaseAnalyticsUtil.getInstance(context).logCustomEvent(Constant.TAB_TOP_UP_PINLESS)
        mView = view
        init()
    }


    private fun init() {
        TopUpWithPlanPresenter(this.requireContext(), this).onGetTopUpWithPlan(getPhoneLogin())

        pinlessBinding.editTextAmount.viewTreeObserver.addOnGlobalLayoutListener {
            pinlessBinding.editTextAmount.requestFocus()
            pinlessBinding.editTextAmount.setSelection(pinlessBinding.editTextAmount.text.length)
        }

        pinlessBinding.editTextTopUpPhoneNumber.setText(SeatelUtils.phoneNumberFormat(mPhone))

        pinlessBinding.editTextAmount.requestFocus()
        pinlessBinding.editTextAmount.setSelection(pinlessBinding.editTextAmount.text.length)
        pinlessBinding.keyboardViewTopUp.setmMaxLenght(30)
        pinlessBinding.keyboardViewTopUp.showKeyBoard(pinlessBinding.editTextAmount)

        // Set touch listeners for EditText fields
        pinlessBinding.editTextTopUpPhoneNumber.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                pinlessBinding.editTextTopUpPhoneNumber.showSoftInputOnFocus = false
                pinlessBinding.keyboardViewTopUp.setmMaxLenght(15)
                pinlessBinding.keyboardViewTopUp.showKeyBoard(v as EditText)
                pinlessBinding.editTextAmount.clearFocus()
                pinlessBinding.editTextTopUpPhoneNumber.requestFocus()
                mIsFocus = false
            }
            false
        }

        pinlessBinding.editTextAmount.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                pinlessBinding.editTextAmount.showSoftInputOnFocus = false
                pinlessBinding.keyboardViewTopUp.setmMaxLenght(6)
                pinlessBinding.keyboardViewTopUp.showKeyBoard(v as EditText)
                pinlessBinding.editTextTopUpPhoneNumber.clearFocus()
                pinlessBinding.editTextAmount.requestFocus()
                mIsFocus = true
                controlKeyBoardHideEditText()
            }
            false
        }

        pinlessBinding.relativeParentPinless.setOnClickListener { hideKeyBoard() }

        pinlessBinding.buttonNext.setOnClickListener {
            hideKeyBoard()
            if (validateControl()) {
                checkPhoneIsInactive(pinlessBinding.editTextTopUpPhoneNumber.text.toString())
            }
        }
    }

    private fun controlKeyBoardHideEditText() {

        pinlessBinding.linearLayoutTopUpBottom.measure(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val bottomParentHeight = pinlessBinding.linearLayoutTopUpBottom.measuredHeight
        val halfScreenHeight = SeatelUtils.getDisplayMetrics(getmContext()).heightPixels * 0.5

        if (halfScreenHeight < bottomParentHeight) {
            var result: Int = bottomParentHeight - halfScreenHeight.toInt()
            result = if (result < 30) 15 else 45
            pinlessBinding.linearLayoutPinless.animate().translationY(
                -SeatelUtils.convertDpToPx(getmContext(), result).toFloat()
            ).duration = 300
        }
    }


    private fun checkPhoneIsInactive(phone: String) {
        object : SeatelJSONObjectRequest(getmContext()) {
            override fun getFunctionName(): String {
                return "seatel/verify-phone-number"
            }

            override fun getMethod(): Int {
                return Request.Method.PUT
            }

            override fun onGetBodyRequest(): String {
                val deliveryAddress = JSONObject()
                try {
                    deliveryAddress.put("phoneNumber", phone.replace(" ", ""))
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
                return deliveryAddress.toString()
            }
        }.setOnErrorListener {
            SeatelAlertDialog.with(getmContext(), SeatelSuperRequest.getErrorMessageFrom(it)).show()
        }.execute {
            startConfirmTopup()
        }
    }

    private fun startConfirmTopup() {
        if (pinlessBinding.editTextAmount == null) return
        val amount = pinlessBinding.editTextAmount.text.toString().toDouble()
        PaymentActivity.lunch(
            getmContext(), pinlessBinding.editTextTopUpPhoneNumber.text.toString(), amount
        )

    }


    private fun validateControl(): Boolean {
        val amount = pinlessBinding.editTextAmount.text.toString().trim()
        var phone = pinlessBinding.editTextTopUpPhoneNumber.text?.trim().toString()
        phone = phone.replace(" ", "")

        var strMessage = ""
        val regex = Regex("\\d+(?:\\.\\d+)?")

        if (TextUtils.isEmpty(phone)) strMessage = getString(R.string.phone_empty)
        else if (phone.startsWith("0") && phone.length < 10 || phone.startsWith("85518") && phone.length < 12 || (!phone.startsWith(
                "0"
            ) && !phone.startsWith(
                "85518"
            ))
        ) strMessage = getString(R.string.please_enter_full_number)
        else if (TextUtils.isEmpty(amount) || !amount.matches(regex)) strMessage =
            getString(R.string.amount_topup_empty)
        else if (!amount.matches(regex)) strMessage = getString(R.string.amount_topup_not_number)
        else if (amount.toDouble() == 0.0) strMessage = getString(R.string.amount_topup_empty)
        else if (amount.toDouble() < 1.0) strMessage =
            getString(R.string.amount_topup_cannot_smaller_1)
        else if (amount.toDouble() > 100.0) strMessage =
            getString(R.string.amount_topup_cannot_bigger_100)

        if (!TextUtils.isEmpty(strMessage)) {
            SeatelAlertDialog.with(getmContext(), strMessage).show()
            return false
        }

        return true
    }


    override fun onGetTopUpWithPlanSucceed(topUpWithPlan: TopUpWithPlanModel) {
        val gridLayoutManager = GridLayoutManager(requireContext(), 4)
        pinlessBinding.recyclerTopUpAmount.layoutManager = gridLayoutManager
        pinlessBinding.recyclerTopUpAmount.adapter =
            TopupWithPlanAdapter(requireContext(), topUpWithPlan.amountList) {
                pinlessBinding.editTextAmount.setText(it.amount.toString())
            }
    }

    override fun onGetTopUpWithPlanFailed(error: VolleyError) {

        SeatelAlertDialog.with(requireActivity(), SeatelSuperRequest.getErrorMessageFrom(error))
            .show()
    }


}
