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.MotionEvent
import android.view.View
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.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.activity.PaymentActivity
import com.seatel.mobilehall.util.*
import kotlinx.android.synthetic.main.fragment_pinless.*
import kotlinx.android.synthetic.main.view_radio_button_top_up.*
import org.json.JSONException
import org.json.JSONObject


class PinlessFragment : BaseFragment() {

    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
    }

    fun getViewPhoneNumber(): View {
        return view_phone_number
    }

    fun getViewAmount(): View {
        return view_amount
    }

    fun getViewButton(): View {
        return button_next
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_pinless)
        FirebaseAnalyticsUtil.getInstance(context).logCustomEvent(Constant.TAB_TOP_UP_PINLESS)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mView = view
        init()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && edit_text_amount != null) {
            showKeyboard()
            if (mIsFocus) edit_text_amount.requestFocus()
            else edit_text_top_up_phone_number.requestFocus()
        }
    }

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

    override fun hideKeyBoard() {
        super.hideKeyBoard()
        keyboard_view_top_up.hideKeyBoard()
        linear_layout_pinless.animate().translationY(0f).duration = 300
    }

    private fun init() {

        keyboard_view_top_up.setmCallBackKeySelect { view, result ->
            if (edit_text_amount.id == view.id)
                setSelectRadioPrice(result)
        }

        setUpRadioButton()
//        showKeyboard()
        edit_text_top_up_phone_number.hint = edit_text_top_up_phone_number.hint
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            edit_text_top_up_phone_number.showSoftInputOnFocus = false
            edit_text_amount.showSoftInputOnFocus = false
        }
        edit_text_amount.setText("5")
        edit_text_amount.setSelection(edit_text_amount.text!!.length)
        edit_text_top_up_phone_number.setText(SeatelUtils.phoneNumberFormat(mPhone))
        keyboard_view_top_up.setmMaxLenght(6)
        keyboard_view_top_up.showKeyBoard(edit_text_amount)
        edit_text_top_up_phone_number.clearFocus()

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

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

        edit_text_amount.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                keyboard_view_top_up.setmMaxLenght(6)
                keyboard_view_top_up.showKeyBoard(v as EditText)
                edit_text_top_up_phone_number.clearFocus()
                edit_text_amount.requestFocus()
                mIsFocus = true
                AnimationUtil.instance!!.expand(radio_group_top_up)

                controlKeyBoardHideEditText()

            }
            false
        }
        edit_text_top_up_phone_number.isFocusable = true
        relative_parent_pinless.setOnClickListener { hideKeyBoard() }
    }

    private fun controlKeyBoardHideEditText() {

        linear_layout_top_up_bottom.measure(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val bottomParentHeight = linear_layout_top_up_bottom.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
            linear_layout_pinless.animate().translationY(
                -SeatelUtils.convertDpToPx(getmContext(), result).toFloat()
            ).duration = 300
        }
    }

    private fun showKeyboard() {

        if (!isKeyboardHided()) return
        mView?.postDelayed(object : Runnable {
            override fun run() {

                if (mIsFocus) {
                    edit_text_amount.requestFocus()
                    keyboard_view_top_up.showKeyBoard(edit_text_amount)
                    controlKeyBoardHideEditText()
                } else keyboard_view_top_up.showKeyBoard(edit_text_top_up_phone_number)
                mView?.removeCallbacks(this)
            }
        }, 200)
    }

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

    private fun setRatioBtnUnSelect() {
        if (mRadioButton != null) {
            mClearSelect = false
            mRadioButton!!.isChecked = false
        }
    }

    private fun validateControl(): Boolean {
        val amount = edit_text_amount.text.toString().trim()
        var phone = edit_text_top_up_phone_number.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
    }

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

        setRadioButtonTextStyle()
        mRadioButton = radio_button_5_dollar
        radio_group_top_up.setOnCheckedChangeListener { radioGroup, id ->
            if (mRadioButton != null) {
                mRadioButton!!.isChecked = false
                mRadioButton!!.setTextColor(
                    ContextCompat.getColor(
                        getmContext(),
                        R.color.colorBlue
                    )
                )
                mRadioButton!!.textSize = 16f
            }

            val radioButton = radioGroup.findViewById<RadioButton>(id) as RadioButton

            if (!mAutoSelect) {
                edit_text_amount.setText(radioButton.tag.toString())
            }
            if (mClearSelect) {
                radioButton.setTextColor(
                    ContextCompat.getColor(
                        getmContext(),
                        android.R.color.white
                    )
                )
                radioButton.isChecked = true
                mRadioButton = radioButton
            }
            mClearSelect = true
            edit_text_amount.setSelection(edit_text_amount.text!!.length)
        }
        button_next.setOnClickListener {
            hideKeyBoard()
            if (validateControl()) {
                checkPhoneIsInactive(edit_text_top_up_phone_number.text.toString())
            }
        }
    }

    private fun startConfirmTopup() {
        if (edit_text_amount == null) return
        val amount = edit_text_amount.text.toString().toDouble()
        PaymentActivity.lunch(getmContext(), edit_text_top_up_phone_number.text.toString(), amount)
        //  ConfirmationActivity.lunch(getmContext(), edit_text_top_up_phone_number.text.toString(), amount, false, "")
    }

    private fun setRadioButtonTextStyle() {

        val topUp = resources.getStringArray(R.array.top_up_amount)
        for (i in 0 until radio_group_top_up.childCount) {
            (radio_group_top_up.getChildAt(i) as RadioButton).text =
                SeatelUtils.fromHtml(topUp[i])
        }

    }
}