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.ui.base.activity.BaseActivity
import com.seatel.mobilehall.util.*
import com.seatel.mobilehall.R
import kotlinx.android.synthetic.main.activity_top_up_amount.*
import kotlinx.android.synthetic.main.layout_selected_number.*
import kotlinx.android.synthetic.main.view_radio_button_top_up.*

/**
 *
 *
 * @author Noel
 * @created on 17-Oct-18
 */
class BuyYesNumberPhaseTopUpActivity : BaseActivity() {
    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 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)
        ) {
            button_skip.visibility = View.VISIBLE
            view_space.visibility = View.VISIBLE
            ctv_note_claim_free_sim.visibility = View.VISIBLE
            button_skip.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)
        text_selected_phone_number.text = phoneNumber
        text_price.text = AppUtils.decimalFormat().format(price)
        setUpRadioButton()
        edit_text_amount.showSoftInputOnFocus = false
        edit_text_amount.setText("5")
        edit_text_amount.setSelection(edit_text_amount.text.length)
        keyboard_view_top_up.setmMaxLenght(6)
        keyboard_view_top_up.showKeyBoard(edit_text_amount)
//        showKeyboard()
    }

    private fun initEvent() {
        keyboard_view_top_up.setmCallBackKeySelect { view, result ->
            if (edit_text_amount.id == view.id)
                setSelectRadioPrice(result)
        }
        onRatioButtonCheckListener()
        button_next.setOnClickListener {
            if (validateControl()) {
                startConfirmTopUp()
            }
        }
        layout_top_up_amount.setOnClickListener {
            hideKeyBoard()
        }
        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_amount.requestFocus()
                mIsFocus = true
                AnimationUtil.instance?.expand(radio_group_top_up)
                controlKeyBoardHideEditText()
            }
            false
        }
    }

    private fun onRatioButtonCheckListener() {
        radio_group_top_up.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) {
                edit_text_amount.setText(radioButton.tag.toString())
            }
            if (mClearSelect) {
                radioButton.setTextColor(ContextCompat.getColor(this, android.R.color.white))
                radioButton.isChecked = true
                mRadioButton = radioButton
            }
            mClearSelect = true
            edit_text_amount.setSelection(edit_text_amount.text.length)
        }
    }

    private fun setUpRadioButton() {
        setRadioButtonTextStyle()
        mRadioButton = radio_button_5_dollar
    }

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

    fun hideKeyBoard() {
        keyboard_view_top_up.hideKeyBoard()
        linear_layout_top_up_amount_top.animate().translationY(0f).duration = 300
    }


//    private fun showKeyboard() {
//        if (!isKeyboardHided()) return
//        layout_top_up_amount.postDelayed(object : Runnable {
//            override fun run() {
//                if (mIsFocus) {
//                    edit_text_amount.requestFocus()
//                    keyboard_view_top_up.showKeyBoard(edit_text_amount)
//                    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 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
        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 = edit_text_amount.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 = edit_text_amount.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 radio_group_top_up.childCount) {
            (radio_group_top_up.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()
        }
    }
}