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

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.databinding.FragmentServicesBinding
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.adapter.RoamingAdapter
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 com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.viewFragmentBinding
import org.json.JSONObject

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

    private var TAG = "ProductFragment::>>>"
    private var selectedButton = 1
    private val mPricePlanList = 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

    //  private lateinit var binding: FragmentServicesBinding

    private val binding by viewFragmentBinding(
        FragmentServicesBinding::inflate
    )

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

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initPresenter()
        init()
        updateButtonColors()
    }

    private fun initPresenter() {
        //AppProductsPresenter(requireContext(), this).onGetAppProducts(getPhoneLogin())
        context?.let {
            AppProductsPresenter(it, this).onGetAppProducts(getPhoneLogin())
        }

    }

    private fun init() {
        if(isAdded){
            binding.apply {
                btnPricePlan.setOnClickListener(this@ServicesFragment)
                btnPackage.setOnClickListener(this@ServicesFragment)
                buttonSwitchPlan.setOnClickListener(this@ServicesFragment)
            }
        }
    }

    private fun setupAdapter(list: ArrayList<AppProductsResponseModel>) {
        handleItemSelection(list[0])
        binding.mRecyclerCategory.adapter = ProductServicePackageAdapter(requireContext(), list) {
            handleItemSelection(it)
        }
    }

    private fun handleItemSelection(plan: AppProductsResponseModel) {
        mCanSubscribe = plan.canSubscribe!!
        mCanChangePlan = plan.canChangePlan!!
        newPlanCode = plan.subscriptionPlan
        switchPlanName = plan.name

        if (plan.code == "rik-reay") {
            RikReayPresenter(requireContext(), this).RikReay()
        } else {
            activity.let {
                if (it != null) {
                    ProductServiceDetailPrsenter(it, this).onProServiceDetail(
                        plan.code!!,
                        getPhoneLogin()
                    )
                }
            }
        }

    }

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

        mPricePlanList.clear()
        mPackageList.clear()

        for (plan in appProductsList) {
            if (plan.type != "plan") {
                mPackageList.add(plan)
            } else {
                mPricePlanList.add(plan)
            }
        }

        // Set the adapter for the category
        if (selectedButton == 1) {
            setupAdapter(mPackageList)
        } else {
            setupAdapter(mPricePlanList)
        }
    }

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

    override fun onProServiceDetailSucceed(valuePackSectionModel: ValuePackSectionModel) {
        if (mCanChangePlan) {
            binding.buttonSwitchPlan.visibility = View.VISIBLE
        } else {
            binding.buttonSwitchPlan.visibility = View.GONE
        }

        when (valuePackSectionModel.type) {
            Constant.LoyKob -> {
                if (isAdded) {
                    binding.mRecyclerDetail.adapter =
                        LoyKobsAdapter(
                            requireContext(),
                            Constant.LoyKob,
                            mCanSubscribe,
                            valuePackSectionModel
                        )
                }
            }

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

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

            else -> {
                binding.mRecyclerDetail.adapter = RoamingAdapter(this,requireContext(),getPhoneLogin(),"any",mCanSubscribe,valuePackSectionModel)
               /* binding.mRecyclerDetail.adapter =
                    LoyKobsAdapter(requireContext(), "any", mCanSubscribe, valuePackSectionModel)*/
            }
        }
    }

    override fun onProServiceDetailFailed(error: VolleyError) {
        val context = context ?: return
        SeatelAlertDialog.with(context, SeatelSuperRequest.getErrorMessageFrom(error)).show()
    }

    override fun onRikReaySucceed(rikReayModel: RikReayModel) {
        Log.d(TAG, "responseRikReay:>>> $rikReayModel")

        binding.buttonSwitchPlan.visibility = if (mCanChangePlan) View.VISIBLE else View.GONE
        binding.mRecyclerDetail.adapter = RikReayAdapter(rikReayModel)
    }

    override fun onRikReayFailed(error: VolleyError) {
        val context = context ?: return
        SeatelAlertDialog.with(context, SeatelSuperRequest.getErrorMessageFrom(error)).show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_price_plan -> {
                selectedButton = 2
                updateButtonColors()
                setupAdapter(mPricePlanList)
            }

            R.id.btn_package -> {
                selectedButton = 1
                updateButtonColors()
                setupAdapter(mPackageList)
            }

            R.id.button_switch_plan -> {
                SeatelAlertDialog.with(
                    requireContext(),
                    "Are you sure you want to switch to $switchPlanName? Your current plan's benefits will be active until its expiry date."
                )
                    .setNegativeButton("No") { dialog, _ -> dialog.dismiss() }
                    .setPositiveButton("Yes") { _, _ -> switchPlan() }
                    .show()
            }
        }
    }

    private fun switchPlan() {
        object : SeatelJSONObjectRequest(requireContext()) {
            override fun getFunctionName() = "switch-plan"
            override fun onGetBodyRequest(): String {
                val obj = JSONObject()
                obj.put("phoneNumber", getPhoneLogin())
                obj.put("newPlanCode", newPlanCode)
                return obj.toString()
            }

            override fun getMethod() = 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)
        }
    }

    private fun updateButtonColors() {

        binding.btnPackage.text = SeatelUtils.translatForDialog(getmContext(),"Packages")
        binding.btnPricePlan.text = SeatelUtils.translatForDialog(getmContext(),"Price Plans")


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

        binding.btnPackage.setBackgroundColor(defaultColor)
        binding.btnPackage.setTextColor(ContextCompat.getColor(requireContext(), R.color.black))
        binding.btnPricePlan.setBackgroundColor(defaultColor)
        binding.btnPricePlan.setTextColor(ContextCompat.getColor(requireContext(), R.color.black))

        when (selectedButton) {
            2 -> {
                binding.btnPricePlan.setBackgroundDrawable(selectedColor)
                binding.btnPricePlan.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.white
                    )
                )
            }

            1 -> {
                binding.btnPackage.setBackgroundDrawable(selectedColor)
                binding.btnPackage.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.white
                    )
                )
            }
        }
    }

    fun scrollToLastPosition() {
        val recyclerView = binding.mRecyclerDetail
        val lastPosition = recyclerView.adapter!!.itemCount + 1
        recyclerView.smoothScrollToPosition(lastPosition)
    }

    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
    ) {

    }
}
