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

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.base.adapter.BaseRecyclerAdapter
import com.seatel.mobilehall.ui.home.adapter.PlanSubscriptionAdapter
import com.seatel.mobilehall.ui.home.interactor.BuyYesSimCardInteractor
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.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.gson.Gson
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import kotlinx.android.synthetic.main.activity_buy_number_plan_subscription.*
import kotlinx.android.synthetic.main.layout_bottom_sheet_next.*
import kotlinx.android.synthetic.main.layout_selected_number.*
import org.json.JSONArray

/**
 *
 *
 * @author Noel
 * @version
 * @created on 17-Oct-18
 */
class BuyYesNumberPhasePlanSubscriptionActivity : BaseActivity(),
    BaseRecyclerAdapter.OnItemClickListener<PlanSubscriptionModel>, BuyYesSimCardInteractor.View {

    private var bottomSheetBehavior: BottomSheetBehavior<LinearLayout>? = null
    private var planSubscriptionAdapter: PlanSubscriptionAdapter? = null
    private var mData = ArrayList<PlanSubscriptionModel>()
    private var mDataTemp = ArrayList<PlanSubscriptionModel>()
    private var phoneNumber: String? = ""
    private var price: Double? = 0.0
    private var cardPrice: Double = 0.0
    private var topUpAmount: Double? = 0.0
    private var selectedPlan = ArrayList<PlanSubscriptionModel>()
    private var mGson = Gson()

    private var buyYesSimCardPresenter: BuyYesSimCardPresenter? = null

    companion object {

        fun launch(
            context: Activity,
            amount: Double,
            phoneNumber: String,
            price: Double,
            cardPrice: Double,
            isClaimFreeSim: Boolean = false,
            isWinPromotionFreeSim: Boolean = false,
            skipTopUp: Boolean = false
        ) {
            context.startActivityForResult(
                Intent(
                    context,
                    BuyYesNumberPhasePlanSubscriptionActivity::class.java
                )
                    .putExtra(Constant.EXTRA_AMOUNT, amount)
                    .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_buy_number_plan_subscription)
        init()
        initEvent()
        getPlanSubscription()
    }

    private fun getPlanSubscription() {
        buyYesSimCardPresenter?.onGetPlanSubscription(this)
    }

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

    override fun getStringToolbarTitle(): String? {
        return "Plan Subscription"
    }

    private fun getPlanCodeSelect(): String {
        if (selectedPlan.size > 0) {
            for (plan in selectedPlan) {
                if (plan.isSelected && !plan.isAddOn)
                    return plan.planCode!!
            }
        }
        return ""
    }

    private fun getAddOnList() {
        mDataTemp.clear()
        mDataTemp.addAll(mData)
        object : SeatelJSONArrayRequest(this@BuyYesNumberPhasePlanSubscriptionActivity) {
            override fun getFunctionName(): String {
                return "seatel/subscription-plans/${getPlanCodeSelect()}/add-ons"
            }

        }.execute {
            val addOnsJson = it as JSONArray
            val dataList = ArrayList<PlanSubscriptionModel>()
            for (i in 0 until addOnsJson.length()) {
                dataList.add(
                    PlanSubscriptionModel(
                        addOnsJson.optJSONObject(i).optString("addOnType", ""),
                        addOnsJson.optJSONObject(i).optString("addOneName", ""),
                        false, addOnsJson.optJSONObject(i).optString("addOnIcon", ""),
                        true, i == 0
                    )
                )
            }
            onAddOnSuccess(dataList)
        }
    }

    private fun onAddOnSuccess(data: List<PlanSubscriptionModel>?) {
        mData.clear()
        mData.addAll(mDataTemp)
        if (data != null) {
            mData.addAll(data)
            planSubscriptionAdapter?.notifyDataSetChanged()
        }
    }

    private fun init() {
        activityEnterRightAnimation()
        buyYesSimCardPresenter = BuyYesSimCardPresenter(this)
        bottomSheetBehavior = BottomSheetBehavior.from(layout_bottom_sheet)
        bottomSheetBehavior?.isHideable = false
        bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
        bindDataFromIntent()
        initRecyclerView()
    }

    private fun bindDataFromIntent() {
        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)
        topUpAmount = intent.getDoubleExtra(Constant.EXTRA_AMOUNT, 0.0)
        text_selected_phone_number.text = phoneNumber
        text_price.text = AppUtils.decimalFormat().format(price!!)
    }

    private fun initRecyclerView() {
        recycler_plan_sub_subscription.setHasFixedSize(true)
        recycler_plan_sub_subscription.layoutManager = LinearLayoutManager(this)
        planSubscriptionAdapter = PlanSubscriptionAdapter(mData)
        recycler_plan_sub_subscription.adapter = planSubscriptionAdapter

    }

    private fun initEvent() {
        button_next.setOnClickListener {
            BuyYesNumberPhaseSummaryActivity.launch(
                this, topUpAmount!!, phoneNumber!!,
                price!!, cardPrice, mGson.toJson(selectedPlan),
                intent.getBooleanExtra(Constant.EXTRA_CLAIM_FREE_SIM, false),
                intent.getBooleanExtra(Constant.EXTRA_WIN_PROMOTION, false),
                intent.getBooleanExtra(Constant.EXTRA_SKIP_TOPUP, false)
            )
        }
        planSubscriptionAdapter?.onItemClickListener = this
    }


    override fun onItemClick(v: View, position: Int, data: PlanSubscriptionModel) {
        if (position != 0) {
            if (data.isAddOn) {
                showDetailAddOn(data.planCode!!, position)
                return
            }
            planSubscriptionAdapter?.getItem(position)?.isSelected =
                !planSubscriptionAdapter?.getItem(position)?.isSelected!!
            val temp = planSubscriptionAdapter?.getItem(position)
            if (planSubscriptionAdapter?.getItem(position)?.isSelected!!) {
                if (!selectedPlan.contains(temp)) {
                    selectedPlan.add(temp!!)
                }
            } else {
                selectedPlan.remove(temp)
            }
            planSubscriptionAdapter?.notifyDataSetChanged()

        }
    }

    private fun checkAddOnInternetPackSelected(price: Double, duration: Int, position: Int) {
        planSubscriptionAdapter?.getItem(position)?.addOnPrice = price
        planSubscriptionAdapter?.getItem(position)?.addOnDuraction = duration
        planSubscriptionAdapter?.getItem(position)?.isSelected = price != 0.0
        val temp = planSubscriptionAdapter?.getItem(position)
        if (planSubscriptionAdapter?.getItem(position)?.isSelected!!) {
            if (!selectedPlan.contains(temp)) {
                selectedPlan.add(temp!!)
            }
        } else {
            if (selectedPlan.contains(temp))
                selectedPlan.remove(temp)
        }
        planSubscriptionAdapter?.notifyDataSetChanged()
    }

    private fun showDetailAddOn(type: String, position: Int) {
        when (type) {
            Constant.INTERNET_PACK -> DataPackActivity.lunchForResult(
                this,
                true,
                this.topUpAmount!!,
                position,
                planSubscriptionAdapter?.getItem(position)?.addOnPrice!!
            )
            Constant.VALUE_PACK -> DataPackActivity.lunchForResult(
                this,
                true,
                this.topUpAmount!!,
                position,
                planSubscriptionAdapter?.getItem(position)?.addOnPrice!!,
                true
            )
            else -> DataPackActivity.lunchForResult(
                this,
                true,
                this.topUpAmount!!,
                position,
                planSubscriptionAdapter?.getItem(position)?.addOnPrice!!
            )
        }
    }

    override fun showWaiting() {
        progress.visibility = View.VISIBLE
    }

    override fun hideWaiting() {
        progress.visibility = View.GONE
    }

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

    override fun showGetPlanSubscriptionSuccess(data: List<PlanSubscriptionModel>?) {
        mDataTemp.clear()
        mDataTemp.addAll(mData)
        mData.clear()
        if (data != null) {
            val temp = PlanSubscriptionModel().apply {
                planCode = Constant.ONE_SUB_PLAN_CODE
            }
            val indexDefault = data.indexOf(temp)
            if (indexDefault != -1) {
                val planOne = data[indexDefault].apply {
                    isSelected = true
                }
                mData.add(planOne)
                selectedPlan.add(planOne)
                (data as ArrayList<PlanSubscriptionModel>).removeAt(indexDefault)
                for (plan in data) {
                    mData.add(plan)
                }
            } else {
                for (plan in data) {
                    if (data.indexOf(plan) == 0) {
                        plan.isSelected = true
                        selectedPlan.add(plan)
                    }
                    mData.add(plan)
                }
            }
            planSubscriptionAdapter?.notifyDataSetChanged()
           // if (topUpAmount!! > 0)
             //   getAddOnList()
        }
    }

    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()
        }
        if (resultCode == Activity.RESULT_OK && requestCode == Constant.PLAN_SUBSCRIPTION) {
            if (data != null) {
                if (data.hasExtra(Constant.INTERNET_PACK_PRICE_SELECT) && data.hasExtra(
                        Constant.ADD_ON_POSITION
                    )
                ) {
                    val position = data.getIntExtra(Constant.ADD_ON_POSITION, 0)
                    val durationAddOn = data.getIntExtra(Constant.ADD_ON_DURACTION, 0)
                    checkAddOnInternetPackSelected(
                        data.getDoubleExtra(
                            Constant.INTERNET_PACK_PRICE_SELECT,
                            0.0
                        ), durationAddOn, position
                    )
                }
            }
        }
    }
}