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.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.ActivityBuyTopUpCardBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.BuyTopUpCardAdapter
import com.seatel.mobilehall.ui.home.interactor.BuyTopUpCardInteractor
import com.seatel.mobilehall.ui.home.model.BuyTopUpCartModel
import com.seatel.mobilehall.ui.home.model.CartModel
import com.seatel.mobilehall.ui.home.model.CartRequestModel
import com.seatel.mobilehall.ui.home.presenter.BuyTopUpCardPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.CustomEditText
import com.seatel.mobilehall.util.customview.DialogAddCart
import com.seatel.mobilehall.util.manager.OrderingManager
import org.json.JSONObject

open class BuyTopUpCardActivity : BaseActivity<ActivityBuyTopUpCardBinding>(),
    BuyTopUpCardInteractor.View,
    BuyTopUpCardAdapter.ShowCustomKeyBoard {

    private val buyTopUpCartModel: ArrayList<BuyTopUpCartModel> = ArrayList()
    private var buyTopUpCardAdapter: BuyTopUpCardAdapter? = null
    private var buyTopUpCardPresenter: BuyTopUpCardPresenter? = null
    private var isSendingRequest = false

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //   setContentView(R.layout.activity_buy_top_up_card)
        init()
        addItems()
        initEvent()
    }

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

    private fun init() {
        buyTopUpCardPresenter = BuyTopUpCardPresenter(this)
        activityEnterRightAnimation()
        buyTopUpCardAdapter = BuyTopUpCardAdapter(this, buyTopUpCartModel, this)
        binding.recyclerViewBuyTopUpCard.adapter = buyTopUpCardAdapter
        binding.recyclerViewBuyTopUpCard.layoutManager = LinearLayoutManager(this)
        addItems()

    }

    private fun addCardToCart(buyTopUpCartModel: BuyTopUpCartModel) {
        val items = ArrayList<CartRequestModel.Scratch>()
        val item = CartRequestModel.Scratch(buyTopUpCartModel.price)
        item.quantity = buyTopUpCartModel.order
        items.add(item)
        val data: CartRequestModel<CartRequestModel.Scratch> = CartRequestModel(
            SeatelSharePreferences.getInstance(this)?.getPhoneLogin(), true, items
        )
        buyTopUpCardPresenter?.onAddCardToCard(this, data)
    }

    override fun focusOnEditText(edit: CustomEditText) {
        binding.keyboardViewTopUpCard.setmMaxLenght(4)
        binding.keyboardViewTopUpCard.showKeyBoard(edit)
    }

    override fun hideKeyBoard() {
        binding.keyboardViewTopUpCard.hideKeyBoard()
    }

    private fun initEvent() {
        buyTopUpCardAdapter?.onItemViewClick = object : BuyTopUpCardAdapter.OnItemViewClick {
            override fun onAddCartClick(position: Int, data: BuyTopUpCartModel) {
                if (!isSendingRequest) {
                    addCardToCart(data)
                }
            }

            override fun onBuyNowClick(position: Int, data: BuyTopUpCartModel) {
                if (data != null)
                    buyTopupCard(data)
            }

        }
    }

    private fun buyTopupCard(data: BuyTopUpCartModel) {
        val dataDeviceOrder = ArrayList<CartModel>()
        val myData = CartModel()

//        val item = CartRequestModel.Device()
        myData.unitPrice = data.price
        myData.scratchCardAmount = data.price
        myData.type = Constant.SRATCH_CARD
        myData.quantity = data.order
        myData.totalPrice = (data.price * data.order)
        myData.isSelected = true
        myData.scratchCardIcon =
            "https://api.yes.com.kh/icons//scratch_card_${data.price.toInt()}.png"
        dataDeviceOrder.add(myData)
        OrderingManager.getInstance().clear()
        OrderingManager.getInstance().cartsModels.addAll(dataDeviceOrder)

        OrderActivity.launch(this, true)
    }

    private fun addItems() {
        buyTopUpCartModel.clear()
//        buyTopUpCartModel.add(BuyTopUpCartModel(50))
//        buyTopUpCartModel.add(BuyTopUpCartModel(20))
        buyTopUpCartModel.add(BuyTopUpCartModel(10))
        buyTopUpCartModel.add(BuyTopUpCartModel(5))
        buyTopUpCartModel.add(BuyTopUpCartModel(2))
        buyTopUpCartModel.add(BuyTopUpCartModel(1))
        buyTopUpCardAdapter?.notifyDataSetChanged()
    }

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

    override fun onBackPressed() {
        if (binding.keyboardViewTopUpCard.isShown) hideKeyBoard()
        else {
            super.onBackPressed()
            activityExitLeftAnimation()
        }
    }

    companion object {
        const val REQUEST_CODE = 1000
        fun lunch(context: Activity) {
            val intent = Intent(context, BuyTopUpCardActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK
            context.startActivityForResult(intent, REQUEST_CODE)
        }
    }

    var dialog: DialogAddCart? = null

    @SuppressLint("InflateParams")
    private fun showDialogItemAddToCart() {
        dialog = DialogAddCart(this)
        dialog?.onItemClick = object : DialogAddCart.OnItemClick {
            override fun onButtonAddToCartClick(view: View) {
                MyCartActivity.launch(this@BuyTopUpCardActivity)
                finish()
            }

            override fun onButtonContinueBuyClick(view: View) {
                addItems()
            }
        }
        dialog?.show()
    }

    override fun showWaiting() {
        isSendingRequest = true
        binding.defaultProfess.progress.visibility = View.VISIBLE
    }

    override fun hideWaiting() {
        isSendingRequest = false
        binding.defaultProfess.progress.visibility = View.GONE
    }

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

    override fun showAddCardToCardSuccess(data: JSONObject?) {
        showDialogItemAddToCart()
    }
}
