package com.seatel.mobilehall.ui.home.fragment

import android.content.Context
import android.os.Build
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 android.widget.RadioButton
import androidx.core.content.ContextCompat
import com.android.volley.Request
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.util.AnimationUtil
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() {

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

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


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

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

    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() {

        pinlessBinding.keyboardViewTopUp.setmCallBackKeySelect { view, result ->
            if (pinlessBinding.editTextAmount.id == view.id) setSelectRadioPrice(result)
        }

        setRadioButtonTextStyle()
        setUpRadioButton()
        pinlessBinding.editTextTopUpPhoneNumber.hint = pinlessBinding.editTextTopUpPhoneNumber.hint
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            pinlessBinding.editTextTopUpPhoneNumber.showSoftInputOnFocus = false
            pinlessBinding.editTextAmount.showSoftInputOnFocus = false
        }
        pinlessBinding.editTextAmount.setText("5")
        pinlessBinding.editTextAmount.setSelection(pinlessBinding.editTextAmount.text!!.length)
        pinlessBinding.editTextTopUpPhoneNumber.setText(SeatelUtils.phoneNumberFormat(mPhone))
        pinlessBinding.keyboardViewTopUp.setmMaxLenght(6)
        pinlessBinding.keyboardViewTopUp.showKeyBoard(pinlessBinding.editTextAmount)
        pinlessBinding.editTextTopUpPhoneNumber.clearFocus()

        pinlessBinding.editTextTopUpPhoneNumber.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                pinlessBinding.editTextAmount.clearFocus()
                pinlessBinding.editTextTopUpPhoneNumber.requestFocus()
                pinlessBinding.keyboardViewTopUp.setmMaxLenght(15)
                pinlessBinding.keyboardViewTopUp.showKeyBoard(v as EditText)
                AnimationUtil.instance?.collapse(pinlessBinding.viewRadio.radioGroupTopUp)
                pinlessBinding.linearLayoutPinless.animate().translationY(0f).duration = 300
                mIsFocus = false
            }
            false
        }
        pinlessBinding.editTextTopUpPhoneNumber.setOnFocusChangeListener { _: View, hasFocus: Boolean ->
            if (!hasFocus) {
                pinlessBinding.editTextTopUpPhoneNumber.setText(
                    SeatelUtils.phoneNumberFormat(
                        pinlessBinding.editTextTopUpPhoneNumber.text?.trim().toString()
                    )
                )
            } else {
                pinlessBinding.editTextTopUpPhoneNumber.setText(
                    pinlessBinding.editTextTopUpPhoneNumber.text?.trim().toString().replace(" ", "")
                )
            }
        }

        mView?.postDelayed(object : Runnable {
            override fun run() {
                pinlessBinding.editTextAmount.requestFocus()
                mView?.removeCallbacks(this)
                controlKeyBoardHideEditText()
            }
        }, 400)

        pinlessBinding.editTextAmount.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                pinlessBinding.keyboardViewTopUp.setmMaxLenght(6)
                pinlessBinding.keyboardViewTopUp.showKeyBoard(v as EditText)
                pinlessBinding.editTextTopUpPhoneNumber.clearFocus()
                pinlessBinding.editTextAmount.requestFocus()
                mIsFocus = true
                AnimationUtil.instance!!.expand(pinlessBinding.viewRadio.radioGroupTopUp)

                controlKeyBoardHideEditText()

            }
            false
        }
        pinlessBinding.editTextTopUpPhoneNumber.isFocusable = true
        pinlessBinding.relativeParentPinless.setOnClickListener { hideKeyBoard() }
    }

    private fun setSelectRadioPrice(priceInPut: String) {
        var flagFound = false
        mAutoSelect = true
        if (mRadioButton != null) {
            setRatioBtnUnSelect()
        }
        for (i in 0 until pinlessBinding.viewRadio.radioGroupTopUp.childCount) {
            val radioBtn = pinlessBinding.viewRadio.radioGroupTopUp.getChildAt(i) as RadioButton
            val price = radioBtn.tag.toString()
            if (TextUtils.equals(price, priceInPut)) {
                radioBtn.isChecked = true
                flagFound = true
                break
            }
        }
        if (!flagFound) mRadioButton = null
        mAutoSelect = false
    }


    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 setRatioBtnUnSelect() {
        if (mRadioButton != null) {
            mClearSelect = false
            mRadioButton!!.isChecked = false
        }
    }

    private fun setRadioButtonTextStyle() {
        val topUp = resources.getStringArray(R.array.top_up_amount)
        for (i in 0 until pinlessBinding.viewRadio.radioGroupTopUp.childCount) {
            (pinlessBinding.viewRadio.radioGroupTopUp.getChildAt(i) as RadioButton).text =
                SeatelUtils.fromHtml(topUp[i])
        }
    }

    private fun setUpRadioButton() {
        mRadioButton = pinlessBinding.viewRadio.radioButton5Dollar
        pinlessBinding.viewRadio.radioGroupTopUp.setOnCheckedChangeListener { radioGroup, _ ->
            if (mRadioButton != null) {
                mRadioButton!!.isChecked = false
                mRadioButton!!.setTextColor(
                    ContextCompat.getColor(
                        getmContext(), R.color.colorBlue
                    )
                )
                mRadioButton!!.textSize = 16f
            }

            val radioButtonId: Int = radioGroup.checkedRadioButtonId
            val radioButton = radioGroup.findViewById<RadioButton>(radioButtonId)

            if (!mAutoSelect) {
                pinlessBinding.editTextAmount.setText(radioButton.tag.toString())
            }
            if (mClearSelect) {
                radioButton.setTextColor(
                    ContextCompat.getColor(
                        getmContext(), android.R.color.white
                    )
                )
                radioButton.isChecked = true
                mRadioButton = radioButton
            }
            mClearSelect = true
            pinlessBinding.editTextAmount.setSelection(pinlessBinding.editTextAmount.text!!.length)
        }

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

        }
    }

    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.toInt() == 0) strMessage = getString(R.string.amount_topup_empty)
        else if (amount.toInt() > 100) strMessage =
            getString(R.string.amount_topup_cannot_bigger_100)

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

        return true
    }

    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
    }


}
