package cpm.com.gskmtorange.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cpm.com.gskmtorange.GetterSetter.CategoryPictureGetterSetter
import cpm.com.gskmtorange.adapter.data.ImageUri
import cpm.com.gskmtorange.databinding.ItemSubcategoryPdBinding

class SubCatPdAdapter(
    val category: String?,
    var context: Context,
    private var subcates: ArrayList<CategoryPictureGetterSetter>?,
    private val btnlistener: BtnClickListener,
) : RecyclerView.Adapter<SubCatPdAdapter.CustomViewHolder>() {
    class CustomViewHolder(view: View) : RecyclerView.ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = CustomViewHolder(
        ItemSubcategoryPdBinding.inflate(LayoutInflater.from(context), parent, false).root
    )

    @SuppressLint(
        "NotifyDataSetChanged", "ClickableViewAccessibility",
        "UseCompatLoadingForDrawables", "SetTextI18n"
    )
    override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
        ItemSubcategoryPdBinding.bind(holder.itemView).apply {
            val subcat = subcates!![position]
            tvSubCategory.text = "$category - ${subcat.suB_CATEGORY}"
            imgStartSession.setOnClickListener {
                btnlistener.onStartSessionClick(_pos = position, data = subcat)
            }

            val savedImagesAdapter =
                SavedImagesAdapter(context = context, images = subcat.imageUris)
            imgRecycler.adapter = savedImagesAdapter
            imgRecycler.setLayoutManager(GridLayoutManager(context, 3))
        }
    }

    override fun getItemCount(): Int {
        return subcates!!.size
    }

    interface BtnClickListener {
        fun onStartSessionClick(_pos: Int, data: CategoryPictureGetterSetter)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addsubCatItems(langList: ArrayList<CategoryPictureGetterSetter>?) {
        subcates = langList
        notifyDataSetChanged()
    }

    fun updateItem(position: Int, uris: List<ImageUri>) {
        subcates!![position].imageUris = (subcates!![position].imageUris
            ?: ArrayList()).apply { addAll(uris as ArrayList<ImageUri>) }
        notifyItemChanged(position)
    }
}