package com.seatel.mobilehall.ui.home.activity

//import kotlinx.android.synthetic.main.frament_pinless.*
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.RadioButton
import androidx.core.content.ContextCompat
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ActivityTopUpAmountBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.util.AnimationUtil
import com.seatel.mobilehall.util.AppUtils
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils

/**
 *
 *
 * @author Noel
 * @created on 17-Oct-18
 */
class BuyYesNumberPhaseTopUpActivity : BaseActivity<ActivityTopUpAmountBinding>() {
    private var mRadioButton: RadioButton? = null
    private var mAutoSelect = false
    private var mClearSelect = true
    private var phoneNumber: String? = ""
    private var price: Double = 0.0
    private var cardPrice: Double = 0.0
    private var mIsFocus: Boolean = true

    companion object {
        fun launch(
            context: Activity,
            phoneNumber: String,
            price: Double,
            cardPrice: Double,
            isClaimFreeSim: Boolean = false,
            isWinPromotionFreeSim: Boolean = false,
            skipTopUp: Boolean = false
        ) {
            context.startActivityForResult(
                Intent(context, BuyYesNumberPhaseTopUpActivity::class.java)
                    .putExtra(Constant.EXTRA_PHONE_NUMBER, phoneNumber)
                    .putExtra(Constant.EXTRA_PHONE_PRICE, price)
                    .putExtra(Constant.EXTRA_SIM_PRICE, cardPrice)
                    .putExtra(Constant.EXTRA_SKIP_TOPUP, skipTopUp)
                    .putExtra(Constant.EXTRA_CLAIM_FREE_SIM, isClaimFreeSim)
                    .putExtra(Constant.EXTRA_WIN_PROMOTION, isWinPromotionFreeSim),
                BuyYesNumberPhaseTwoActivity.REUEST_CODE
            )
        }
    }

    override fun getViewBinding(): ActivityTopUpAmountBinding {
        return ActivityTopUpAmountBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // setContentView(R.layout.activity_top_up_amount)
        super.activityEnterRightAnimation()
        init()
        initEvent()
    }

    override fun getToolbarTitle(): String {
        return getString(R.string.top_up_amount)
    }

    private fun init() {
        if (intent.getBooleanExtra(Constant.EXTRA_CLAIM_FREE_SIM, false) ||
            intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false) ||
            intent.getBooleanExtra(Constant.EXTRA_SKIP_TOPUP, false)
        ) {
            binding.buttonSkip.visibility = View.VISIBLE
            binding.viewSpace.visibility = View.VISIBLE
            binding.ctvNoteClaimFreeSim.visibility = View.VISIBLE
            binding.buttonSkip.setOnClickListener {
                BuyYesNumberPhasePlanSubscriptionActivity.launch(
                    this,
                    0.0,
                    phoneNumber!!,
                    price,
                    cardPrice,
                    intent.getBooleanExtra(Constant.EXTRA_CLAIM_FREE_SIM, false),
                    intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false),
                    intent.getBooleanExtra(Constant.EXTRA_SKIP_TOPUP, false)
                )
            }
        }
        phoneNumber = intent.getStringExtra(Constant.EXTRA_PHONE_NUMBER)
        price = intent.getDoubleExtra(Constant.EXTRA_PHONE_PRICE, 0.0)
        cardPrice = intent.getDoubleExtra(Constant.EXTRA_SIM_PRICE, 0.0)
        binding.layoutSelectedNumber.textSelectedPhoneNumber.text = phoneNumber
        binding.layoutSelectedNumber.textPrice.text = AppUtils.decimalFormat().format(price)
        setUpRadioButton()
        binding.editTextAmount.showSoftInputOnFocus = false
        binding.editTextAmount.setText("5")
        binding.editTextAmount.setSelection(binding.editTextAmount.text.length)
        binding.keyboardViewTopUp.setmMaxLenght(6)
        binding.keyboardViewTopUp.showKeyBoard(binding.editTextAmount)
//        showKeyboard()
    }

    private fun initEvent() {
        binding.keyboardViewTopUp.setmCallBackKeySelect { view, result ->
            if (binding.editTextAmount.id == view.id)
                setSelectRadioPrice(result)
        }
        onRatioButtonCheckListener()
        binding.buttonNext.setOnClickListener {
            if (validateControl()) {
                startConfirmTopUp()
            }
        }
        binding.layoutTopUpAmount.setOnClickListener {
            hideKeyBoard()
        }

        binding.editTextAmount.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                binding.keyboardViewTopUp.setmMaxLenght(6)
                binding.keyboardViewTopUp.showKeyBoard(v as EditText)
                binding.editTextAmount.requestFocus()
                mIsFocus = true

                AnimationUtil.instance?.expand(binding.layoutRadioButtonTopUp.radioGroupTopUp)
                controlKeyBoardHideEditText()
            }
            false
        }
    }

    private fun onRatioButtonCheckListener() {
        binding.layoutRadioButtonTopUp.radioGroupTopUp.setOnCheckedChangeListener { radioGroup, id ->
            if (mRadioButton != null) {
                mRadioButton!!.isChecked = false
                mRadioButton!!.setTextColor(ContextCompat.getColor(this, R.color.colorBlue))
                mRadioButton!!.textSize = 16f
            }

            val radioButton = radioGroup.findViewById(id) as RadioButton

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

    private fun setUpRadioButton() {
        setRadioButtonTextStyle()
        mRadioButton = binding.layoutRadioButtonTopUp.radioButton5Dollar
    }

    fun isKeyboardHided(): Boolean {
        return binding.keyboardViewTopUp.visibility == View.GONE
    }

    fun hideKeyBoard() {
        binding.keyboardViewTopUp.hideKeyBoard()
        binding.linearLayoutTopUpAmountTop.animate().translationY(0f).duration = 300
    }


//    private fun showKeyboard() {
//        if (!isKeyboardHided()) return
//        layout_top_up_amount.postDelayed(object : Runnable {
//            override fun run() {
//                if (mIsFocus) {
//                    binding.editTextAmount.requestFocus()
//                    binding.keyboardViewTopUp.showKeyBoard(binding.editTextAmount)
//                    controlKeyBoardHideEditText()
//                }
//                layout_top_up_amount?.removeCallbacks(this)
//            }
//        }, 200)
//    }

    private fun setSelectRadioPrice(priceInPut: String) {
        var flagFound = false
        mAutoSelect = true
        if (mRadioButton != null) {
            setRatioBtnUnSelect()
        }
        for (i in 0 until binding.layoutRadioButtonTopUp.radioGroupTopUp.childCount) {
            val radioBtn =
                binding.layoutRadioButtonTopUp.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 setRatioBtnUnSelect() {
        if (mRadioButton != null) {
            mClearSelect = false
            mRadioButton!!.isChecked = false
        }
    }

    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(this).heightPixels * 0.5
//
//        if (halfScreenHeight < bottomParentHeight) {
//            var result: Int = bottomParentHeight - halfScreenHeight.toInt()
//            result = if (result < 30) 15 else 45
//            linear_layout_top_up_amount_top.animate().translationY(-SeatelUtils.convertDpToPx(this, result).toFloat()).duration = 300
//        }
    }

    private fun validateControl(): Boolean {
        val amount = binding.editTextAmount.text.toString().trim()
        var strMessage = ""
        when {
            TextUtils.isEmpty(amount) -> strMessage = getString(R.string.amount_topup_empty)
            amount.toInt() == 0 -> strMessage = getString(R.string.amount_topup_empty)
            amount.toInt() > 100 -> strMessage = getString(R.string.amount_topup_cannot_bigger_100)
        }
        if (!TextUtils.isEmpty(strMessage)) {
            SeatelAlertDialog.with(this, strMessage).show()
            return false
        }
        return true
    }


    private fun startConfirmTopUp() {
        val amount = binding.editTextAmount.text.toString().toDouble()
        BuyYesNumberPhasePlanSubscriptionActivity.launch(
            this, amount, phoneNumber!!, price, cardPrice,
            intent.getBooleanExtra(Constant.EXTRA_CLAIM_FREE_SIM, false),
            intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false)
        )
    }

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

    override fun onBackPressed() {
        super.onBackPressed()
        activityExitLeftAnimation()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == BuyYesNumberPhaseTwoActivity.REUEST_CODE) {
            setResult(resultCode, data)
            finish()
        }
    }
}