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

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.SpannableString
import android.text.style.StyleSpan
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.android.volley.VolleyError
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.databinding.ActivityConfirmBuyDataPackBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.interactor.BuyDataPackFreedomInteractor
import com.seatel.mobilehall.ui.home.model.ValuePackSectionModel
import com.seatel.mobilehall.ui.home.model.ValuePackTableModel
import com.seatel.mobilehall.ui.home.presenter.BuyDataPackFreedomPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import java.text.DecimalFormat

class ConfirmBuyDataPackActivity : BaseActivity<ActivityConfirmBuyDataPackBinding>(),
    BuyDataPackFreedomInteractor.View {

    private var isDataFreedom: Boolean = false
    private var isValuePack: Boolean = false
    private var isFortunePlan: Boolean = false
    private var isVipFortunePlan: Boolean = false
    private var isloykob: Boolean = false
    private var isTypeAddon: String = ""
    private var mDataValuePack: ValuePackTableModel? = null
    private lateinit var mBuyDataPackFreedomPresenter: BuyDataPackFreedomPresenter
    private lateinit var mBuyDataPackFreedomInteractor: BuyDataPackFreedomInteractor.View
    private var mAmountPost: Double = 0.0
    private var mDataSize = ""
    private var mAccountNumber = ""
    private var isAllowBackPressed = true
    private var mTypeBuy = ""

    //update
    private var name: String = ""
    private var type: String = ""
    private var validity: String = ""
    private var fee: String = ""
    private var data: String = ""
    private var isAddON: Boolean = false
    private var pricePlanCode: String = ""
    private var requestTime: String? = null

    //  private var valuePackSectionModel: ValuePackSectionModel? = null


    override fun onBuyDataSucceed() {
        SuccessBuyDataPackActivity.launch(this, name, data, isAddON)/* if (isValuePack || isFortunePlan || isVipFortunePlan) mDataValuePack?.let {
             when {
                 isFortunePlan -> {
                     SuccessBuyDataPackActivity.lunchFromValuePack(this, it, isFortunePlan = true)
                 }
                 isVipFortunePlan -> {
                     SuccessBuyDataPackActivity.lunchFromValuePack(this, it, isVipFortunePlan = true)
                 }
                 else -> SuccessBuyDataPackActivity.lunchFromValuePack(this, it)
             }
         }
         else SuccessBuyDataPackActivity.lunch(this, mDataSize, mAccountNumber, isDataFreedom)*/
        finish()
    }

    override fun onBuyDataFailed(error: VolleyError) {
        Log.d("---buyDataFailed", "onBuyDataFailed: $error")
        binding.errorView.visibility = View.GONE
        SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(error)).show()
        binding.buttonOk.isEnabled = true
        isAllowBackPressed = true
    }

    private fun startBuyData() {
        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)

        if (fee.substring(1).toDouble() == 0.5 && !isValuePack && !isFortunePlan) {

            mBuyDataPackFreedomPresenter.onBuyData(
                getPhoneLogin(), type, 0.1, isAddON, pricePlanCode, requestTime!!
            )


        } else mBuyDataPackFreedomPresenter.onBuyData(
            getPhoneLogin(),
            type,
            fee.substring(1).toDouble(),
            isAddON,
            pricePlanCode,
            requestTime!!
        )
        //note: if amount 0.5 then change it to 0.1 for CRM(do it for CRM)
        /*if (mAmountPost == 0.5 && !isValuePack && !isFortunePlan) {
            mBuyDataPackFreedomPresenter.onBuyData(getPhoneLogin(), mTypeBuy, 0.1, isTypeAddon)
        } else
            mBuyDataPackFreedomPresenter.onBuyData(
                getPhoneLogin(),
                mTypeBuy,
                mAmountPost,
                isTypeAddon
            )*/
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterFadeInAnimation()
        //  setContentView(R.layout.activity_confirm_buy_data_pack)

        val tsLong = System.currentTimeMillis() / 1000
        requestTime = tsLong.toString()

        mBuyDataPackFreedomInteractor = this
        mBuyDataPackFreedomPresenter =
            BuyDataPackFreedomPresenter(this, mBuyDataPackFreedomInteractor)
        getData()
        init()

    }

    private fun setupView() {
        isDataFreedom = intent.getBooleanExtra(Constant.LAUNCH_FROM, false)
        isValuePack = intent.getBooleanExtra("IS_VALUE_PACK", false)
        isFortunePlan = intent.getBooleanExtra("IS_FORTUNE_PACK", false)
        isVipFortunePlan = intent.getBooleanExtra("IS_VIP_FORTUNE_PACK", false)
        isloykob = intent.getBooleanExtra("IS_LOY_KOB", false)
        isTypeAddon = intent.getStringExtra("add-on").toString()
        mAccountNumber =
            if (intent.hasExtra(Constant.MPAY_ACCOUNT_TRANFER)) intent.getStringExtra(Constant.MPAY_ACCOUNT_TRANFER)
                .toString()
            else getPhoneLogin()
        var datePlan = 0
        if (intent.hasExtra(Constant.DURATION_PLAN_DATE_SELECT)) datePlan =
            intent.getIntExtra(Constant.DURATION_PLAN_DATE_SELECT, 0)
        val dayStr = if (datePlan > 1) SeatelUtils.translatForDialog(
            this, "Days"
        ) else SeatelUtils.translatForDialog(this, "Day")
        val dataMB: Double
        val amountMB: String
        Log.d("---isValuePack", "onCreate: $isValuePack")

        when {
            isDataFreedom -> {
                mTypeBuy = Constant.FREEDOM_INTERNET //"freedom-data"
                val amountTransfer: Long = intent.getLongExtra(Constant.MPAY_AMOUNT, 0)
                mAmountPost = amountTransfer.toDouble()
                dataMB = SeatelUtils.calcualateFreedomDataInput(amountTransfer)
                val convertSucess = SeatelUtils.displayDataFreedomDataInput(dataMB)
                val dataMBDisplay = convertSucess[0]
                mDataSize = convertSucess[0].toString()

                val str = "$dataMBDisplay${convertSucess[1]} = $"
                val wordDataBuy = SpannableString("$str$amountTransfer")
                wordDataBuy.setSpan(StyleSpan(Typeface.BOLD), 0, dataMBDisplay.length, 0)
                binding.cvDataBuy.text = wordDataBuy

                binding.ctvDeduct.text = "${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.we_will_deduct)
                    )
                } $$amountTransfer ${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.from_ur_balance)
                    )
                }"
            }

            isValuePack -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    mTypeBuy = Constant.VALUE_PACK
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    val amount = mDataValuePack?.priceChange?.replace("$", "")
                    val strAmount = "${formatterPrice.format(amount?.toDouble())}"

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "Value Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    binding.cvDataValidValuePack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        binding.cvDataBuy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        binding.cvDataValidValuePack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        binding.cvDataBuy.text = Html.fromHtml(str)
                        binding.cvDataValidValuePack.text = Html.fromHtml(strValid)
                    }
                    binding.ctvDeduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            isFortunePlan -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    binding.ctvBuyData.text = "Buy Fortune Pack"
                    mTypeBuy = Constant.FORTUNE_PACK
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    //val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    //val amount = mDataValuePack?.priceChange
                    val strAmount = mDataValuePack?.priceChange

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "Fortune Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    binding.cvDataValidValuePack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        binding.cvDataBuy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        binding.cvDataValidValuePack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        binding.cvDataBuy.text = Html.fromHtml(str)
                        binding.cvDataValidValuePack.text = Html.fromHtml(strValid)
                    }
                    binding.ctvDeduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            isVipFortunePlan -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    binding.ctvBuyData.text = "Buy VIP Fortune Pack"
                    mTypeBuy = Constant.VIP_FORTUNE_PACK
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    //val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    //val amount = mDataValuePack?.priceChange
                    val strAmount = mDataValuePack?.priceChange

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "VIP Fortune Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    binding.cvDataValidValuePack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        binding.cvDataBuy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        binding.cvDataValidValuePack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        binding.cvDataBuy.text = Html.fromHtml(str)
                        binding.cvDataValidValuePack.text = Html.fromHtml(strValid)
                    }
                    binding.ctvDeduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            isloykob -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    binding.ctvBuyData.text = Constant.IS_LOY_KOB
                    mTypeBuy = Constant.IS_LOY_KOB
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    //val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    //val amount = mDataValuePack?.priceChange
                    val strAmount = mDataValuePack?.priceChange

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "VIP Fortune Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    binding.cvDataValidValuePack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        binding.cvDataBuy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        binding.cvDataValidValuePack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        binding.cvDataBuy.text = Html.fromHtml(str)
                        binding.cvDataValidValuePack.text = Html.fromHtml(strValid)
                    }
                    binding.ctvDeduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            else -> {
                mTypeBuy = Constant.INTERNET_PACK //"datapack"
                val price = intent.getStringExtra(Constant.PRICE_VALUE)
                if (price!!.isNotEmpty()) mAmountPost = price.substring(1).toDouble()
                amountMB = intent.getStringExtra(Constant.MPAY_AMOUNT).toString()
                mDataSize = amountMB

//                binding.cvDataBuy.text = "$datePlan$dayStr (\$$price = $amountMB)"

                val str = "<font size=5>$datePlan$dayStr </font>  <b>( ${
                    SeatelUtils.formatDecimalNumber(
                        mAmountPost, "$#.##"
                    )
                } = $amountMB )</b> "
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    binding.cvDataBuy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                } else binding.cvDataBuy.text = Html.fromHtml(str)

                binding.ctvDeduct.text = "${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.we_will_deduct)
                    )
                } $price ${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.from_ur_balance)
                    )
                }"
            }
        }
        binding.tvPhoneNumber.text = SeatelUtils.phoneNumberFormat(mAccountNumber)
        binding.buttonOk.setOnClickListener {
            startBuyData()
            binding.buttonOk.isEnabled = false
            isAllowBackPressed = false

        }

        if (isDataFreedom) {
            binding.ctvBuyData.text = getString(R.string.buy_freedom_internet)
        } else if (isValuePack || isFortunePlan) binding.ctvBuyData.text = "Activate"

        binding.imageViewBack.setOnClickListener {
            onBackPressed()
        }
    }

    private fun getData() {
        name = intent.getStringExtra("NAME").toString()
        type = intent.getStringExtra("TYPE").toString()
        validity = intent.getStringExtra("VALIDITY").toString()
        fee = intent.getStringExtra("FEE").toString()
        data = intent.getStringExtra("DATA").toString()
        isAddON = intent.getBooleanExtra("ADDON", false)
        pricePlanCode = intent.getStringExtra("PRICEPLANCODE").toString()
    }

    private fun init() {
        if (isAddON) binding.ctvBuyData.text =
            SeatelUtils.translatForDialog(this, "Buy $name Add On")
        else binding.ctvBuyData.text = SeatelUtils.translatForDialog(this, "Buy $name")
        binding.cvDataBuy.text = SeatelUtils.translatForDialog(this, "$fee")
        binding.tvPhoneNumber.text = getPhoneLogin()

        //    valuePackSectionModel = intent.getSerializableExtra("valuePackSectionModel") as ValuePackSectionModel
        //  binding.ctvBuyData.text = SeatelUtils.translatForDialog(this,"Buy ${valuePackSectionModel!!.name}")
        //  binding.cvDataBuy.text = SeatelUtils.translatForDialog(this, "${valuePackSectionModel!!.valuePackSecTwoModel.table[0].valuePrice}")
        //  Log.d("TAG::>>>", "init: $valuePackSectionModel")

        binding.ctvDeduct.text = "${
            SeatelUtils.translatForDialog(
                this, getString(R.string.we_will_deduct)
            )
        } $fee ${
            SeatelUtils.translatForDialog(
                this, getString(R.string.from_ur_balance)
            )
        }"
        binding.buttonOk.setOnClickListener {
            startBuyData()
            binding.buttonOk.isEnabled = false
            isAllowBackPressed = false

        }

        binding.imageViewBack.setOnClickListener {
            onBackPressed()
        }
    }

    private fun resetButtonOkMargin() {
        val paramLayout = binding.buttonOk.layoutParams as ViewGroup.MarginLayoutParams
        paramLayout.bottomMargin = 40
        binding.buttonOk.layoutParams = paramLayout
    }


    override fun onBackPressed() {
        if (isAllowBackPressed) {
            super.onBackPressed()
            super.activityExitFadeOutAnimation()
        }
    }

    companion object {
        fun lunchFromFreedom(context: Context, amount: Long, account: String, freedom: Boolean) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra(Constant.MPAY_AMOUNT, amount)
            intent.putExtra(Constant.MPAY_ACCOUNT_TRANFER, account)
            intent.putExtra(Constant.LAUNCH_FROM, freedom)
            context.startActivity(intent)
        }

        fun launchData(context: Context, valuePackSectionModel: ValuePackSectionModel) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra("valuePackSectionModel", valuePackSectionModel)
            context.startActivity(intent)
        }

        fun launch(
            context: Context,
            name: String,
            type: String,
            validity: String,
            fee: String,
            data: String,
            pricePlanCode: String,
            isAddOn: Boolean
        ) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra("NAME", name)
            intent.putExtra("TYPE", type)
            intent.putExtra("VALIDITY", validity)
            intent.putExtra("FEE", fee)
            intent.putExtra("DATA", data)
            intent.putExtra("ADDON", isAddOn)
            intent.putExtra("PRICEPLANCODE", pricePlanCode)
            context.startActivity(intent)

        }


        fun lunchFromDataPack(
            context: Context,
            amountMB: String,
            pricetMB: String,
            account: String,
            dayPlan: Int,
            freedom: Boolean,
            type: String
        ) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra(Constant.MPAY_AMOUNT, amountMB)
            intent.putExtra(Constant.PRICE_VALUE, pricetMB)
            intent.putExtra(Constant.MPAY_ACCOUNT_TRANFER, account)
            intent.putExtra(Constant.DURATION_PLAN_DATE_SELECT, dayPlan)
            intent.putExtra(Constant.LAUNCH_FROM, freedom)
            intent.putExtra("add-on", type)
            context.startActivity(intent)
        }


        fun lunchFromValuePack(
            context: Context,
            dataValuePack: ValuePackTableModel,
            type: String,
            isFortunePlan: Boolean = false,
            isVipFortunePlan: Boolean = false,
            isloykob: Boolean = false
        ) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            when {
                isFortunePlan -> {
                    intent.putExtra("IS_FORTUNE_PACK", true)
                }

                isVipFortunePlan -> {
                    intent.putExtra("IS_VIP_FORTUNE_PACK", true)
                }

                isloykob -> {
                    intent.putExtra("IS_LOY_KOB", true)
                }

                else -> {
                    intent.putExtra("IS_VALUE_PACK", true)
                }
            }
            intent.putExtra("VALUE_PACK_DATA", Gson().toJson(dataValuePack))
            intent.putExtra("add-on", type)
            context.startActivity(intent)

        }
    }

    override fun isDisplayBackgroundBlur(): Boolean {
        return true
    }

    override fun isDisplayToolbar(): Boolean {
        return false
    }
}
