package com.example.tabbuy.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.tabbuy.data.local.entity.KeranjangEntity
import com.example.tabbuy.databinding.ItemKeranjangBinding

class KeranjangAdapter(
    private val onUpdateClick: (KeranjangEntity) -> Unit,
    private val onDeleteClick: (KeranjangEntity) -> Unit
) : RecyclerView.Adapter<KeranjangAdapter.KeranjangViewHolder>() {

    private var items = emptyList<KeranjangEntity>()

    class KeranjangViewHolder(val binding: ItemKeranjangBinding) : RecyclerView.ViewHolder(binding.root)

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

    override fun onBindViewHolder(holder: KeranjangViewHolder, position: Int) {
        val currentItem = items[position]
        
        holder.binding.tvProdukId.text = currentItem.namaProduk
        holder.binding.tvHargaKeranjang.text = "Rp ${currentItem.harga}"
        holder.binding.tvJumlah.text = currentItem.jumlah.toString()

        Glide.with(holder.itemView.context)
            .load(currentItem.gambar)
            .placeholder(android.R.drawable.ic_menu_gallery)
            .into(holder.binding.ivProduct)

        holder.binding.btnPlus.setOnClickListener {
            val newItem = currentItem.copy(jumlah = currentItem.jumlah + 1)
            onUpdateClick(newItem)
        }

        holder.binding.btnMinus.setOnClickListener {
            if (currentItem.jumlah > 1) {
                val newItem = currentItem.copy(jumlah = currentItem.jumlah - 1)
                onUpdateClick(newItem)
            }
        }

        holder.binding.btnDelete.setOnClickListener {
            onDeleteClick(currentItem)
        }
    }

    override fun getItemCount() = items.size

    fun setData(newItems: List<KeranjangEntity>) {
        items = newItems
        notifyDataSetChanged()
    }
}
