package com.seatel.mobilehall.ui.packages.fragment

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import com.android.volley.Request
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.activity.SuccessBuyDataPackActivity
import com.seatel.mobilehall.ui.home.interactor.AppProductsInteractor
import com.seatel.mobilehall.ui.home.interactor.ProductServiceButtonClick
import com.seatel.mobilehall.ui.home.interactor.ProductServiceDetailInteractor
import com.seatel.mobilehall.ui.home.model.AppProductsResponseModel
import com.seatel.mobilehall.ui.home.model.ValuePackSectionModel
import com.seatel.mobilehall.ui.home.model.ValuePackTableModel
import com.seatel.mobilehall.ui.home.presenter.AppProductsPresenter
import com.seatel.mobilehall.ui.home.presenter.ProductServiceDetailPrsenter
import com.seatel.mobilehall.ui.packages.adapter.InternationalAdapter
import com.seatel.mobilehall.ui.packages.adapter.LoyKobsAdapter
import com.seatel.mobilehall.ui.packages.adapter.OnePlanDetailAdapter
import com.seatel.mobilehall.ui.packages.adapter.ProductServicePackageAdapter
import com.seatel.mobilehall.ui.packages.adapter.RikReayAdapter
import com.seatel.mobilehall.ui.packages.interactor.RikReayInteractor
import com.seatel.mobilehall.ui.packages.model.RikReayModel
import com.seatel.mobilehall.ui.packages.presenter.RikReayPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import kotlinx.android.synthetic.main.fragment_test.btn_package
import kotlinx.android.synthetic.main.fragment_test.btn_plan
import kotlinx.android.synthetic.main.fragment_test.button_switch_plan
import kotlinx.android.synthetic.main.fragment_test.mRecyclerCategory
import kotlinx.android.synthetic.main.fragment_test.mRecyclerDetail
import org.json.JSONObject

class TestFragment : BaseFragment(), AppProductsInteractor.View,
    ProductServiceDetailInteractor.View, RikReayInteractor.View, ProductServiceButtonClick,
    View.OnClickListener {

    private var TAG = "ProductFragment::>>>"
    private var selectedButton = 1
    private val mPlanList = ArrayList<AppProductsResponseModel>()
    private val mPackageList = ArrayList<AppProductsResponseModel>()
    private var mCanSubscribe = false
    private var mCanChangePlan = false
    private var switchPlanName: String? = null
    private var newPlanCode: String? = null


    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_test)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initPresenter()
        init()
        updateButtonColors()
    }

    private fun initPresenter() {
        // request products list
        AppProductsPresenter(requireContext(), this).onGetAppProducts(getPhoneLogin())
    }

    private fun init() {

        btn_plan.setOnClickListener(this)
        btn_package.setOnClickListener(this)
        button_switch_plan.setOnClickListener(this)

    }

    // get products list
    override fun onGetAppProductsSucceed(appProductsList: ArrayList<AppProductsResponseModel>) {
        Log.d(TAG, "responseProductsList: $appProductsList")

        mPlanList.clear()
        mPackageList.clear()
        for (plan in appProductsList) {
            if (plan.type == "plan") {

                mPlanList.add(plan)
                // request products detail
                mPlanList.let {
                    it.forEachIndexed { index, appProductsResponseModel ->
                        if (index == 0) {
                            if (appProductsResponseModel.code == "rik-reay") {
                                RikReayPresenter(requireContext(), this).RikReay()
                            } else ProductServiceDetailPrsenter(
                                requireActivity(), this
                            ).onProServiceDetail(plan.code!!, getPhoneLogin())

                            mCanSubscribe = appProductsResponseModel.canSubscribe!!
                            mCanChangePlan = appProductsResponseModel.canChangePlan!!
                            newPlanCode = appProductsResponseModel.subscriptionPlan
                            switchPlanName = appProductsResponseModel.name
                        }
                    }
                }

                mRecyclerCategory.adapter =
                    ProductServicePackageAdapter(requireContext(), mPlanList) {
                        if (it.code!! == "rik-reay") {
                            RikReayPresenter(requireContext(), this).RikReay()
                        } else ProductServiceDetailPrsenter(
                            requireActivity(), this
                        ).onProServiceDetail(it.code!!, getPhoneLogin())
                        mCanSubscribe = it.canSubscribe!!
                        mCanChangePlan = it.canChangePlan!!
                        newPlanCode = it.subscriptionPlan
                        switchPlanName = it.name
                    }


            } else {
                mPackageList.add(plan)
            }


        }

    }

    override fun onGetAppProductsFailed(error: VolleyError) {
        SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error)).show()
    }

    override fun buttonActive(
        dataValuePack: ValuePackTableModel,
        amountMB: String,
        pricetMB: String,
        account: String,
        dayPlan: Int,
        type: String
    ) {

    }

    override fun confirmBuy(
        validity: String, fee: String, data: String, pricePlanCode: String, isAddon: Boolean
    ) {

    }

    //get detail of products
    override fun onProServiceDetailSucceed(valuePackSectionModel: ValuePackSectionModel) {
        Log.d(TAG, "responseProductsDetailList: $valuePackSectionModel")
        if (mCanChangePlan) button_switch_plan.visibility = View.VISIBLE
        else button_switch_plan.visibility = View.GONE
        valuePackSectionModel.let {
            when (it.type) {
                Constant.LoyKob -> {
                    mRecyclerDetail.adapter = LoyKobsAdapter(
                        requireContext(), Constant.LoyKob, mCanSubscribe, valuePackSectionModel
                    )
                }

                Constant.OnePlan -> {
                    mRecyclerDetail.adapter =
                        OnePlanDetailAdapter(requireContext(), valuePackSectionModel)
                }

                Constant.InternationalCall -> {
                    mRecyclerDetail.adapter =
                        InternationalAdapter(requireContext(), valuePackSectionModel)
                }

                else -> {
                    mRecyclerDetail.adapter = LoyKobsAdapter(
                        requireContext(), "any", mCanSubscribe, valuePackSectionModel
                    )
                }
            }
        }
    }

    override fun onProServiceDetailFailed(error: VolleyError) {
        SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error)).show()
    }

    override fun onRikReaySucceed(rikReayModel: RikReayModel) {
        Log.d(TAG, "responseRikReay:>>> $rikReayModel ")
        if (mCanChangePlan) button_switch_plan.visibility = View.VISIBLE
        else button_switch_plan.visibility = View.GONE
        mRecyclerDetail.adapter = RikReayAdapter(rikReayModel)
    }

    override fun onRikReayFailed(error: VolleyError) {
        SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error)).show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_plan -> {
                selectedButton = 1
                updateButtonColors()
                mRecyclerCategory.adapter =
                    ProductServicePackageAdapter(requireContext(), mPlanList) {
                        if (it.code!! == "rik-reay") {
                            RikReayPresenter(requireContext(), this).RikReay()
                        } else ProductServiceDetailPrsenter(
                            requireActivity(), this
                        ).onProServiceDetail(it.code!!, getPhoneLogin())
                        mCanSubscribe = it.canSubscribe!!
                        mCanChangePlan = it.canChangePlan!!
                        newPlanCode = it.subscriptionPlan
                        switchPlanName = it.name
                    }
                mPlanList.let {
                    it.forEachIndexed { index, appProductsResponseModel ->
                        if (index == 0) {
                            if (appProductsResponseModel.code == "rik-reay") {
                                RikReayPresenter(requireContext(), this).RikReay()
                            } else ProductServiceDetailPrsenter(
                                requireActivity(), this
                            ).onProServiceDetail(appProductsResponseModel.code!!, getPhoneLogin())
                            mCanSubscribe = appProductsResponseModel.canSubscribe!!
                            mCanChangePlan = appProductsResponseModel.canChangePlan!!
                            newPlanCode = appProductsResponseModel.subscriptionPlan
                            switchPlanName = appProductsResponseModel.name
                        }
                    }
                }
            }

            R.id.btn_package -> {
                selectedButton = 2
                updateButtonColors()
                mRecyclerCategory.adapter =
                    ProductServicePackageAdapter(requireContext(), mPackageList) {

                        ProductServiceDetailPrsenter(
                            requireActivity(), this
                        ).onProServiceDetail(it.code!!, getPhoneLogin())

                        mCanSubscribe = it.canSubscribe!!
                        mCanChangePlan = it.canChangePlan!!
                        newPlanCode = it.subscriptionPlan
                        switchPlanName = it.name
                    }
                mPackageList.let {
                    it.forEachIndexed { index, appProductsResponseModel ->
                        if (index == 0) {
                            ProductServiceDetailPrsenter(
                                requireActivity(), this
                            ).onProServiceDetail(appProductsResponseModel.code!!, getPhoneLogin())
                            mCanSubscribe = appProductsResponseModel.canSubscribe!!
                            mCanChangePlan = appProductsResponseModel.canChangePlan!!
                            newPlanCode = appProductsResponseModel.subscriptionPlan
                            switchPlanName = appProductsResponseModel.name
                        }

                    }
                }


            }

            R.id.button_switch_plan -> {
                SeatelAlertDialog.with(
                    requireContext(),
                    "Are you sure you want to switch to the ${switchPlanName.toString()}? Your current plan's benefits will be active until its expiry date."
                ).setNegativeButton("No") { dialog, _ ->
                    dialog.dismiss()
                }.setPositiveButton("Yes") { _, _ ->
                    object : SeatelJSONObjectRequest(context) {
                        override fun getFunctionName(): String {
                            return "switch-plan"
                        }

                        override fun onGetBodyRequest(): String {
                            val obj = JSONObject()
                            obj.put("phoneNumber", getPhoneLogin())
                            obj.put("newPlanCode", newPlanCode)

                            return obj.toString()
                        }

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

                    }.setOnErrorListener {
                        SeatelAlertDialog.with(
                            requireContext(), SeatelSuperRequest.getErrorMessageFrom(it)
                        ).show()
                    }.execute {
                        val message = it as JSONObject
                        val mMessage = message.optString("message")
                        SuccessBuyDataPackActivity.launchSwitchPlan(
                            requireContext(), mMessage.toString()
                        )

                    }
                }.show()
            }
        }
    }

    private fun updateButtonColors() {

        val defaultColor = ContextCompat.getColor(requireContext(), R.color.white)
        val selectedColor =
            ContextCompat.getDrawable(requireContext(), R.drawable.bg_button_round_service)

        btn_plan.setBackgroundColor(defaultColor)
        btn_plan.setTextColor(ContextCompat.getColor(requireContext(), R.color.black))
        btn_package.setBackgroundColor(defaultColor)
        btn_package.setTextColor(ContextCompat.getColor(requireContext(), R.color.black))

        when (selectedButton) {
            1 -> {
                btn_plan.setBackgroundDrawable(selectedColor)
                btn_plan.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
            }

            2 -> {
                btn_package.setBackgroundDrawable(selectedColor)
                btn_package.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
            }
        }
    }


}