package com.seatel.mobilehall.ui.home.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ItemTopupAmountBinding
import com.seatel.mobilehall.ui.home.model.Amount

class TopupWithPlanAdapter(
    private val mContext: Context,
    private val amountList: ArrayList<Amount>,
    private val onSelect: (Amount) -> Unit
) : RecyclerView.Adapter<TopupWithPlanAdapter.ViewHolder>() {

    private var selectedPosition = -1 // Track the selected position

    inner class ViewHolder(val binding: ItemTopupAmountBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(amount: Amount, isSelected: Boolean) {
            binding.tvAmount.text = "${amount.amount} USD"
            binding.tvValidity.text = amount.validity

            // Highlight the selected item
            if (isSelected) {
                binding.frameContent.setBackgroundColor(mContext.getColor(R.color.colorPrimary))
                binding.tvAmount.setTextColor(mContext.getColor(R.color.white))
                binding.tvValidity.setTextColor(mContext.getColor(R.color.white))


            } else {
                binding.frameContent.setBackgroundColor(mContext.getColor(R.color.white))
                binding.tvAmount.setTextColor(mContext.getColor(R.color.colorPrimary))
                binding.tvValidity.setTextColor(mContext.getColor(R.color.colorGray))

            }
        }
    }

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

    override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
        val amount = amountList[position]
        val isSelected = position == selectedPosition

        holder.bind(amount, isSelected)

        // Handle item click
        holder.itemView.setOnClickListener {
            selectedPosition = position // Update the selected position
            notifyDataSetChanged() // Refresh the RecyclerView to update the UI
            onSelect(amount) // Notify the listener
        }
    }

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

    // Method to update the dataset
    fun updateData(newAmountList: List<Amount>) {
        amountList.clear()
        amountList.addAll(newAmountList)
        notifyDataSetChanged()
    }

    // Method to get the selected item
    fun getSelectedItem(): Amount? {
        return if (selectedPosition != -1) amountList[selectedPosition] else null
    }
}