package com.seatel.mobilehall.ui.packages.adapter

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.VolleyError
import com.bumptech.glide.Glide
import com.facebook.internal.Utility.logd
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.ItemLayoutRoamingBinding
import com.seatel.mobilehall.ui.base.adapter.BaseAdapter
import com.seatel.mobilehall.ui.home.activity.ConfirmBuyDataPackActivity
import com.seatel.mobilehall.ui.home.model.ValuePackSectionModel
import com.seatel.mobilehall.ui.packages.fragment.ServicesFragment
import com.seatel.mobilehall.util.dialogannouncement.CustomDialog
import org.json.JSONObject


class RoamingAdapter(
    private var serviceFragment: ServicesFragment,
    private var mContext: Context,
    private var phoneLogin: String,
    private var type: String,
    private var canSubscribe: Boolean,
    private var appProductsDetail: ValuePackSectionModel
) : BaseAdapter<RoamingAdapter.ViewHolder>() {

    private var isSwitchChangingState = false
    private var isRoaming = false
    private var isSpecialSim = false

    class ViewHolder(var binding: ItemLayoutRoamingBinding) : RecyclerView.ViewHolder(binding.root)


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RoamingAdapter.ViewHolder {
        val binding = ItemLayoutRoamingBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return 1
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val context = holder.binding.root.context

        Glide.with(mContext)
            .load(appProductsDetail.dataPackDetailSecOneModel.mobileImageUrl)
            .into(holder.binding.ivBanner)

        holder.binding.tvMainTitle.text = appProductsDetail.valuePackSecTwoModel.title


        isSpecialSim = SeatelSharePreferences.getInstance(mContext)?.isSpecialSimcard()!!

        if (!isSpecialSim) {
            holder.binding.tvRemindTitle.visibility = View.VISIBLE
            holder.binding.tvRemindTitle.apply {
                settings.javaScriptEnabled = true
                loadDataWithBaseURL(
                    null,
                    appProductsDetail.valuePackSecTwoModel.subTitle,
                    "text/html",
                    "UTF-8",
                    null
                )
                settings.defaultFontSize = 12

            }
        } else holder.binding.tvRemindTitle.visibility = View.GONE

        holder.binding.customTextView.apply {
            settings.javaScriptEnabled = true
            loadDataWithBaseURL(
                null,
                appProductsDetail.valuePackSecThreeModel.description,
                "text/html",
                "UTF-8",
                null
            )
            settings.defaultFontSize = 12
        }



        holder.binding.swOnOff.isChecked =
            SeatelSharePreferences.getInstance(mContext)?.isRoamingActivation()!!

        holder.binding.swOnOff.setOnCheckedChangeListener { _, isChecked ->
            if (isSwitchChangingState) return@setOnCheckedChangeListener
            isRoaming = SeatelSharePreferences.getInstance(mContext)?.isRoamingActivation()!!
            isSpecialSim = SeatelSharePreferences.getInstance(mContext)?.isSpecialSimcard()!!
            holder.binding.swOnOff.isEnabled = false
            if (isSpecialSim) {
                handleSpecialSimToggle(context, isChecked, isRoaming, holder.binding)
            } else {
                isSwitchChangingState = true
                holder.binding.swOnOff.isChecked = isRoaming
                isSwitchChangingState = false

                val dialog =
                    CustomDialog(
                        mContext,
                        "",
                        mContext.getString(R.string.not_special_sim_msg),
                        R.drawable.ic_warning, "OK", ""
                    ).setPositiveButton(
                        "Ok",
                        DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() })
                dialog.show()

            }
            holder.binding.swOnOff.isEnabled = true
        }



        Glide.with(mContext)
            .load(appProductsDetail.dataPackDetailSecOneModel.mobileImageUrl2)
            .into(holder.binding.ivBannerTwo)



        holder.binding.roamingRecycler.layoutManager =
            LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)
        holder.binding.roamingRecycler.adapter =
            RoamingListAdapter(
                mContext,
                appProductsDetail.valuePackSecTwoModel.table
            ) { item ->


                holder.binding.layoutDetail.postDelayed({
                    animateItem(holder.binding.layoutDetail)
                }, 100)

                serviceFragment.scrollToLastPosition()

                holder.binding.layoutDetail.visibility = ViewGroup.VISIBLE
                holder.binding.tvData.text = item.priceChange
                Glide.with(context).load(item.icon).into(holder.binding.icLogo)

                holder.binding.btnSubscribe.setOnClickListener {

                    val checkIsRoaming =
                        SeatelSharePreferences.getInstance(mContext)?.isRoamingActivation()

                    if (!checkIsRoaming!!) {
                        val dialog =
                            CustomDialog(
                                mContext,
                                "Attention",
                                mContext.getString(R.string.inactive_roaming_service_msg),
                                R.drawable.ic_warning, "Ok", ""
                            ).setPositiveButton(
                                "Ok",
                                DialogInterface.OnClickListener { dialog, which ->
                                    dialog.dismiss()
                                    holder.binding.layoutDetail.postDelayed({
                                        animateItem(holder.binding.layoutDetail)
                                    }, 100)
                                })
                        dialog.show()
                    } else
                        if (item.activateBtn) {
                            val name = item.title
                            val type = appProductsDetail.type
                            val validity = item.validityDate
                            val fee = item.valuePrice
                            val data = item.priceChange
                            val pricePlanCode = item.code
                            val isAddOn = false

                            ConfirmBuyDataPackActivity.launch(
                                mContext,
                                name,
                                type,
                                validity,
                                fee,
                                data,
                                pricePlanCode,
                                isAddOn
                            )
                        }

                }
            }


    }


    private fun animateItem(view: View) {
        // Set the initial position below the screen
        view.translationY = view.height.toFloat()
        // Animate the view to its normal position
        view.animate()
            .translationY(0f)
            .setDuration(300) // Duration for the animation
            .setInterpolator(AccelerateDecelerateInterpolator()) // Interpolator for smoothness
            .start()
    }

    private fun handleSpecialSimToggle(
        context: Context,
        isChecked: Boolean,
        isRoaming: Boolean,
        binding: ItemLayoutRoamingBinding
    ) {

        if (!isRoaming) {

            val dialog =
                CustomDialog(
                    mContext,
                    "Confirmation",
                    mContext.getString(R.string.active_roaming_service_msg),
                    R.drawable.ic_confirmation, "Confirm", "NO"
                ).setPositiveButton("Confirm", DialogInterface.OnClickListener { dialog, which ->
                    requestRoamingService(
                        phoneNumber = phoneLogin,
                        type = appProductsDetail.type,
                        action = "activate",
                        onSuccess = {
                            updateSwitchState(binding, isChecked)
                            showActivationSuccessDialog(context)
                        },
                        onFailure = {
                            revertSwitchState(binding, isRoaming)
                            showToast(context, SeatelSuperRequest.getErrorMessageFrom(it))
                        }
                    )
                    dialog.dismiss()
                }).setNegativeButton("NO", DialogInterface.OnClickListener { dialog, which ->
                    revertSwitchState(binding, isRoaming)
                    dialog.dismiss()
                })
            dialog.show()


        } else {
            val dialog =
                CustomDialog(
                    mContext,
                    "Confirmation", mContext.getString(R.string.confirm_deactivate_roaming_msg),
                    R.drawable.ic_confirmation, "Confirm", "NO"
                ).setPositiveButton("Confirm", DialogInterface.OnClickListener { dialog, _ ->
                    requestRoamingService(
                        phoneNumber = phoneLogin,
                        type = appProductsDetail.type,
                        action = "activate",
                        onSuccess = {
                            updateSwitchState(binding, isChecked)
                            showDeactivationDialog(context)
                        },
                        onFailure = {
                            revertSwitchState(binding, isRoaming)
                            showToast(context, SeatelSuperRequest.getErrorMessageFrom(it))
                        }
                    )
                    dialog.dismiss()
                }).setNegativeButton("NO", DialogInterface.OnClickListener { dialog, _ ->
                    revertSwitchState(binding, isRoaming)
                    dialog.dismiss()
                })

            dialog.show()

        }
    }

    private fun updateSwitchState(binding: ItemLayoutRoamingBinding, isChecked: Boolean) {
        SeatelSharePreferences.getInstance(mContext)
            ?.setRoamingActivation(isChecked)
        isSwitchChangingState = true
        binding.swOnOff.isChecked = isChecked
        isSwitchChangingState = false
        binding.swOnOff.isEnabled = true
    }

    private fun revertSwitchState(binding: ItemLayoutRoamingBinding, previousState: Boolean) {
        isSwitchChangingState = true
        binding.swOnOff.isChecked = previousState
        isSwitchChangingState = false
        binding.swOnOff.isEnabled = true
    }

    private fun showActivationSuccessDialog(context: Context) {

        val dialog =
            CustomDialog(
                mContext,
                "Attention",
                mContext.getString(R.string.active_roaming_service_success_msg),
                R.drawable.ic_warning, "OK", ""
            ).setPositiveButton(mContext.getString(R.string.enable_roaming_msg),
                DialogInterface.OnClickListener { dialog, _ ->
                    val intent = Intent(Settings.ACTION_DATA_ROAMING_SETTINGS)
                    context.startActivity(intent)
                    dialog.dismiss()
                })
        dialog.show()


    }

    private fun showDeactivationDialog(context: Context) {

        val dialog =
            CustomDialog(
                mContext,
                "Attention",
                "You’ve successfully deactivated the Roaming Service. Please disable the 'Data Roaming' function in your device settings.",
                R.drawable.ic_warning, "Confirm", ""
            ).setPositiveButton(
                "Disable Data Roaming in Settings",
                DialogInterface.OnClickListener { dialog, which ->
                    val intent = Intent(Settings.ACTION_DATA_ROAMING_SETTINGS)
                    context.startActivity(intent)
                    dialog.dismiss()
                })
        dialog.show()

    }

    private fun showToast(context: Context, message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }


    private fun requestRoamingService(
        phoneNumber: String,
        type: String,
        action: String,
        onSuccess: () -> Unit,
        onFailure: (VolleyError) -> Unit
    ) {
        object : SeatelJSONObjectRequest(mContext) {
            override fun getFunctionName(): String = "seatel/buy-service"

            override fun getMethod(): Int = Request.Method.POST

            override fun onGetBodyRequest(): String {
                val obj = JSONObject()
                obj.put("phoneNumber", phoneNumber)
                obj.put("type", type)
                obj.put("action", action)
                return obj.toString()
            }
        }.setOnErrorListener {
            onFailure(it)
        }.execute {
            logd("requestRoamingService", "Response: ${Gson().toJson(it)}")
            onSuccess()
        }
    }


}