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

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.databinding.ActivityMyCartBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.MyCartAdapter
import com.seatel.mobilehall.ui.home.model.SeatelShopLocationModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.util.view.OrderBottomBarView
import org.json.JSONObject


class MyCartActivity : BaseActivity<ActivityMyCartBinding>(), View.OnClickListener,
    OrderBottomBarView.OnButtonClick,
    OrderingManager.OrderCallback {

    private var icDelete: MenuItem? = null
    private var cartAdapter: MyCartAdapter? = null

    override fun onCheckShipInsurance(isCheck: Boolean) {
    }

    override fun onCartModifyQty() {
        binding.orderBottomBar.setTotal(
            OrderingManager.getInstance().totalSelectedPrice,
            OrderingManager.getInstance().selectedCartsModels.size
        )
        cartAdapter?.notifyDataSetChanged()
    }

    override fun onDeliveryData(seatelShopLocationModel: SeatelShopLocationModel?) {
    }

    override fun onClick() {
        OrderActivity.launch(this)
    }

    override fun onCartModify() {
//        Log.d("data", Gson().toJson(OrderingManager.getInstance().cartsModels))
        binding.orderBottomBar.setTotal(
            OrderingManager.getInstance().totalSelectedPrice,
            OrderingManager.getInstance().selectedCartsModels.size
        )
        icDelete?.isVisible = OrderingManager.getInstance().selectedCartsModels.size > 0
    }

    override fun onClick(v: View?) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            Constant.CART_DEVICE_DETAIL -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    cartAdapter = MyCartAdapter(
                        this,
                        binding.cartErrorView,
                        binding.recyclerViewCart,
                        binding.swipeRefreshLayout
                    )
                    binding.recyclerViewCart.adapter = cartAdapter
//                    if (data.hasExtra(Constant.IntentKeys.IS_UPDATE_DEVICE)) {
//
//                    }
                }
            }
        }

    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // setContentView(R.layout.activity_my_cart)
        OrderingManager.getInstance().orderCallback = this
        activityEnterUpAnimation()

        binding.cartErrorView.errorMessage = getString(R.string.no_item_on_my_cart)
        binding.orderBottomBar.setOnButtonClick(this)

        binding.recyclerViewCart.layoutManager = LinearLayoutManager(this)
        cartAdapter = MyCartAdapter(
            this,
            binding.cartErrorView,
            binding.recyclerViewCart,
            binding.swipeRefreshLayout
        )
        binding.recyclerViewCart.adapter = cartAdapter
    }

    fun getErrorView(): ErrorHandleView {
        return binding.cartErrorView
    }

    override fun isDisplayHome(): Boolean {
        return true
    }

    override fun isShowBackButtonLeft(): Boolean {
        return true
    }

    override fun isCancelBackType(): Boolean {
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        OrderingManager.getInstance().clear()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        activityExitDownAnimation()

    }

    override fun onResume() {
        super.onResume()
        OrderingManager.getInstance().orderCallback = this
    }

    override fun onPause() {
        super.onPause()
        OrderingManager.getInstance().orderCallback = null
    }

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

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_my_cart, menu)
        icDelete = menu?.findItem(R.id.recycle_bin)
        icDelete?.isVisible = false
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.recycle_bin -> {
                deleteCart()
                true
            }

            else -> {
                super.onOptionsItemSelected(item)
            }
        }
    }

    fun getBottomBar(): OrderBottomBarView {
        return binding.orderBottomBar
    }

    companion object {
        fun launch(context: Context) {
            val intent = Intent(context, MyCartActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    private fun deleteCart() {
        SeatelAlertDialog.with(this, "Are you sure you want to delete?")
            .setPositiveButton("Yes") { _, _ ->
                object : SeatelJSONObjectRequest(this@MyCartActivity) {

                    override fun getFunctionName(): String {
                        return "carts/items"
                    }

                    override fun onGetUrlParams(requestParams: RequestParams?) {
                        requestParams?.put("phoneNumber", getPhoneLogin())
                        requestParams?.put("ids", OrderingManager.getInstance().selectedIds)
                        super.onGetUrlParams(requestParams)
                    }

                    override fun getMethod(): Int {
                        return Request.Method.DELETE
                    }

                }.execute {
                    if ((it as JSONObject).optString("message") == "OK") {
                        cartAdapter = MyCartAdapter(
                            this,
                            binding.cartErrorView,
                            binding.recyclerViewCart,
                            binding.swipeRefreshLayout
                        )
                        binding.recyclerViewCart.adapter = cartAdapter
                    }
                }
            }.setNegativeButton("No") { dialog, _ -> dialog.dismiss() }.show()
    }
}
