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

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.VolleyError
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.ActivityBuyNumberSumarryBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.BuySimSummaryAdapter
import com.seatel.mobilehall.ui.home.interactor.BuyYesSimCardInteractor
import com.seatel.mobilehall.ui.home.model.BuySimSummaryItemModel
import com.seatel.mobilehall.ui.home.model.CartModel
import com.seatel.mobilehall.ui.home.model.CartRequestModel
import com.seatel.mobilehall.ui.home.model.PlanSubscriptionModel
import com.seatel.mobilehall.ui.home.presenter.BuyYesSimCardPresenter
import com.seatel.mobilehall.util.AppUtils
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.DialogAddCart
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.util.manager.PlanSubscriptionRequestModel
import org.json.JSONObject

/**
 *
 *
 * @author Noel
 * @version
 * @created on 18-Oct-18
 */
class BuyYesNumberPhaseSummaryActivity : BaseActivity<ActivityBuyNumberSumarryBinding>(),
    BuyYesSimCardInteractor.View {

    private var amount: Double? = 0.0
    private var phoneNumber: String? = ""
    private var price: Double? = 0.0
    private var cardPrice: Double = 0.0
    private var gsonStringPlan = ""
    private var selectedPlan: ArrayList<PlanSubscriptionModel>? = null
    private var mData = ArrayList<BuySimSummaryItemModel>()
    private var mAdapter: BuySimSummaryAdapter? = null
    private var typeToken = object : TypeToken<List<PlanSubscriptionModel>>() {
    }.type
    private var buyYesSimPresenter: BuyYesSimCardPresenter? = null
    private val mGson = Gson()

    companion object {
        fun launch(
            activity: Activity,
            amount: Double,
            phone: String,
            price: Double,
            cardPrice: Double,
            planList: String,
            isClaimFreeSim: Boolean = false,
            isWinPromotionFreeSim: Boolean = false,
            skipTopUp: Boolean = false
        ) {
            activity.startActivityForResult(
                Intent(
                    activity,
                    BuyYesNumberPhaseSummaryActivity::class.java
                ).apply {
                    putExtra(Constant.EXTRA_AMOUNT, amount)
                    putExtra(Constant.EXTRA_PHONE_NUMBER, phone)
                    putExtra(Constant.EXTRA_PHONE_PRICE, price)
                    putExtra(Constant.EXTRA_SIM_PRICE, cardPrice)
                    putExtra(Constant.EXTRA_PLAN_LIST, planList)
                    putExtra(Constant.EXTRA_SKIP_TOPUP, skipTopUp)
                    putExtra(Constant.EXTRA_CLAIM_FREE_SIM, isClaimFreeSim)
                    putExtra(Constant.EXTRA_WIN_PROMOTION, isWinPromotionFreeSim)
                }, BuyYesNumberPhaseTwoActivity.REUEST_CODE
            )
        }
    }

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

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_buy_number_sumarry)
        init()
        initEvent()
        initRecycler()
    }

    override fun onDestroy() {
        super.onDestroy()
        buyYesSimPresenter?.onDestroy()
    }

    override fun getStringToolbarTitle(): String? {
        return resources.getString(R.string.summary)
    }

    private fun init() {
        if (intent.getBooleanExtra(Constant.EXTRA_CLAIM_FREE_SIM, false) ||
            intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false)
        ) {
            binding.layoutAddCartBuy.btnAddToCart.visibility = View.GONE
        }
        buyYesSimPresenter = BuyYesSimCardPresenter(this)
        activityEnterRightAnimation()
        getDataFromIntent()
    }

    private fun initEvent() {
        binding.layoutAddCartBuy.btnAddToCart.setOnClickListener { onAddCartClick() }
        binding.layoutAddCartBuy.btnBuy.setOnClickListener { onBuySimClick() }
    }

    private fun onBuySimClick() {
        val dataDeviceOrder = ArrayList<CartModel>()
        val myData = CartModel()
        var promotionItemId = ""
//        val item = CartRequestModel.Device()

        myData.simCardNumber = phoneNumber
        myData.type = Constant.SIM_CARD
        myData.quantity = 1
        myData.cardPrice = cardPrice //OrderingManager.getInstance().simPriceDefault
        if (intent.getBooleanExtra(Constant.EXTRA_CLAIM_FREE_SIM, false) ||
            intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false)
        ) {
            myData.cardPrice = 0.0
        }
        if (selectedPlan != null && selectedPlan!!.size > 0) {
            myData.planCode = selectedPlan?.get(0)!!.planCode
            myData.planIcon = selectedPlan?.get(0)!!.planIcon
            myData.planName = selectedPlan?.get(0)!!.planName
        }
        if (price != null) {
            myData.unitPrice = price as Double
            myData.totalPrice = (price as Double) + (amount as Double) + myData.cardPrice
            if (intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false)) {
                myData.totalPrice = myData.totalPrice - myData.unitPrice
                promotionItemId = OrderingManager.getInstance().promotionItemId
            }
        }
        if (amount != null)
            myData.topUpAmount = amount as Double

        myData.planSubscription = PlanSubscriptionRequestModel(getPlanName(), getAddOnList())
        myData.isSelected = true
        dataDeviceOrder.add(myData)

        OrderingManager.getInstance().clear()
        OrderingManager.getInstance().cartsModels.addAll(dataDeviceOrder)
        if (promotionItemId.isNotEmpty())
            OrderingManager.getInstance().setPromotionItem(promotionItemId)
        OrderingManager.getInstance().skipTopUp =
            intent.getBooleanExtra(Constant.EXTRA_SKIP_TOPUP, false)
        OrderActivity.launch(
            this,
            intent.getBooleanExtra(Constant.EXTRA_CLAIM_FREE_SIM, false),
            intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false)
        )
    }

    private fun getPlanName(): String {
        if (selectedPlan != null && selectedPlan!!.size > 0) {
            return selectedPlan?.get(0)!!.planName!!
        }
        return ""
    }

    private fun getAddOnList(): ArrayList<PlanSubscriptionRequestModel.AddOns> {
        val dataAddOn = ArrayList<PlanSubscriptionRequestModel.AddOns>()
        for (plan in selectedPlan!!) {
            if (plan.isAddOn && plan.isSelected) {
                dataAddOn.add(
                    PlanSubscriptionRequestModel.AddOns(
                        plan.addOnPrice,
                        plan.planName,
                        plan.planIcon,
                        plan.addOnDuraction
                    )
                )
            }
        }
        return dataAddOn
    }

    private fun onAddCartClick() {
        val planSubscription = PlanSubscriptionRequestModel(getPlanName(), getAddOnList())
        buyYesSimPresenter?.addSimCardToCard(
            this,
            CartRequestModel(
                SeatelSharePreferences.getInstance(this)?.getPhoneLogin(),
                true,
                ArrayList<CartRequestModel.SimCard>().apply {
                    this.add(
                        CartRequestModel.SimCard(
                            planSubscription, amount!!.toInt(),
                            phoneNumber
                        )
                    )
                })
        )

//        buyYesSimPresenter?.addSimCardToCard(this, CartRequestModel(SeatelSharePreferences.getConstant(this).phoneLogin, ArrayList<CartRequestModel.SimCard>().apply {
//            this.add(CartRequestModel.SimCard(Constant.MySubscription.ONE_SUB_PLAN_CODE, amount!!.toInt(),
//                    phoneNumber))
//        }))
    }

    private fun getDataFromIntent() {
        intent.apply {
            amount = getDoubleExtra(Constant.EXTRA_AMOUNT, 0.0)
            phoneNumber = getStringExtra(Constant.EXTRA_PHONE_NUMBER)
            price = getDoubleExtra(Constant.EXTRA_PHONE_PRICE, 0.0)
            cardPrice = getDoubleExtra(Constant.EXTRA_SIM_PRICE, 0.0)
            gsonStringPlan = getStringExtra(Constant.EXTRA_PLAN_LIST).toString()
        }
        selectedPlan = mGson.fromJson(gsonStringPlan, typeToken)
        bindDataFromIntent()
    }

    private fun bindDataFromIntent() {
        binding.layoutSelectedNumber.textSelectedPhoneNumber.text = phoneNumber
        binding.layoutSelectedNumber.textPrice.text = AppUtils.decimalFormat().format(price)
    }

    private fun initRecycler() {
        binding.recyclerBuySimSummary.setHasFixedSize(true)
        binding.recyclerBuySimSummary.layoutManager = LinearLayoutManager(this)
        mAdapter = BuySimSummaryAdapter(mData)
        binding.recyclerBuySimSummary.adapter = mAdapter
        addItems()
    }

    private fun addItems() {
        mData.clear()
        mData.add(BuySimSummaryItemModel.TopUpAmount().apply {
            title = resources.getString(R.string.top_up_amount_to_active_your_number)
            amount = this@BuyYesNumberPhaseSummaryActivity.amount
        })

        if (selectedPlan != null) {
            for (plan in selectedPlan!!) {
                mData.add(BuySimSummaryItemModel.PlanSubscription().apply {
                    title = if (plan.isAddOn) resources.getString(R.string.add_on)
                    else resources.getString(R.string.plan_subscription)
                    name = plan.planName
                    code = plan.planCode
                    planIcon = plan.planIcon
                    icon = plan.icon
                    addOnPrice = plan.addOnPrice
                    isAddOn = plan.isAddOn
                    duration = plan.addOnDuraction
                })
            }

        }
        mAdapter?.notifyDataSetChanged()
    }

    @SuppressLint("InflateParams")
    private fun showDialogItemAddToCart() {
        val dialog = DialogAddCart(this)
        dialog.onItemClick = object : DialogAddCart.OnItemClick {
            override fun onButtonAddToCartClick(view: View) {
                setResultOKCard(true)
            }

            override fun onButtonContinueBuyClick(view: View) {
                setResultOKCard(false)
            }
        }
        dialog.show()
    }

    private fun enableUI(enabled: Boolean) {
        binding.layoutAddCartBuy.btnBuy.isEnabled = enabled
        binding.layoutAddCartBuy.btnAddToCart.isEnabled = enabled
    }

    override fun showWaiting() {
        super.showWaiting()
        binding.layoutDefaultProgress.progress.visibility = View.VISIBLE
        enableUI(false)
    }

    override fun hideWaiting() {
        super.hideWaiting()
        binding.layoutDefaultProgress.progress.visibility = View.GONE
        enableUI(true)
    }

    override fun showAddSimToCardFailed(throwable: VolleyError) {
        super.showAddSimToCardFailed(throwable)
        SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(throwable)).show()
    }

    override fun showAddSimToCardSuccess(data: JSONObject?) {
        super.showAddSimToCardSuccess(data)
        showDialogItemAddToCart()
    }

    private fun setResultOKCard(cart: Boolean) {
        val intent = Intent()
        intent.putExtra(Constant.EXTRA_IS_CART, cart)
        setResult(Activity.RESULT_OK, intent)
    }
}