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

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
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

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


    override fun onBuyDataSucceed() {
        SuccessBuyDataPackActivity.launch(this, name, data, isAddON)
        finish()
    }

    override fun onBuyDataFailed(error: VolleyError) {
        Log.d("---buyDataFailed", "onBuyDataFailed: ${error.message}")
        binding.errorView.visibility = View.GONE
        if ( SeatelSuperRequest.getErrorMessageFrom(error).equals("Balance is not enough or no effective balance.")) {
            SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(error))
                .setPositiveButton("Top UP",
                    DialogInterface.OnClickListener { dialog, which ->
                        TopUpActivity.lunch(this)
                    }).show()
        } else {
            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!!
        )
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterFadeInAnimation()

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

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

    }


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

        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
    }
}
