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

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ItemLayoutRoamingListBinding
import com.seatel.mobilehall.ui.base.adapter.BaseAdapter
import com.seatel.mobilehall.ui.home.model.ValuePackTableModel

class RoamingListAdapter(
    private val context: Context,
    private val tableList: List<ValuePackTableModel>,
    private val onItemClick: (item: ValuePackTableModel) -> Unit
) : BaseAdapter<RoamingListAdapter.ViewHolder>() {

    private var selectedItemPosition: Int = -1 // Holds the position of the selected item

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

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

    override fun onBindViewHolder(holder: RoamingListAdapter.ViewHolder, position: Int) {
        val item = tableList[position]

        // Bind data to views
        holder.binding.tvFee.text = item.valuePrice
        holder.binding.tvValidity.text = item.validityDate
        holder.binding.tvTitle.text = item.title

        // Check if the item is selected and update the background accordingly
        val isSelected = position == selectedItemPosition
        val background = if (isSelected) {
            ContextCompat.getDrawable(holder.itemView.context, R.drawable.bg_roaming_round_pink)
        } else {
            ContextCompat.getDrawable(holder.itemView.context, R.drawable.bg_roaming_round_gray)
        }
        holder.binding.bgFrame.background = background


        // Handle item click to update selection state
        holder.itemView.setOnClickListener {
            if (selectedItemPosition != position) {
                selectedItemPosition = position
                notifyDataSetChanged() // Refresh the entire list to update backgrounds
            }
            onItemClick(item)
        }
    }

    override fun getItemCount(): Int = tableList.size
}
