package com.example.bnsptest.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.bnsptest.data.local.dao.Product
import com.example.bnsptest.databinding.ItemCartBinding

class CartAdapter(
    private val onIncrease: (Product) -> Unit,
    private val onDecrease: (Product) -> Unit
) : ListAdapter<Product, CartAdapter.CartViewHolder>(DiffCallback) {

    class CartViewHolder(private val binding: ItemCartBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(item: Product, onIncrease: (Product) -> Unit, onDecrease: (Product) -> Unit) {
            binding.tvCartProductName.text = item.name
            binding.tvCartProductPrice.text = "Rp${item.price}"
            binding.tvQuantity.text = item.quantity.toString()

            Glide.with(binding.ivCartProduct.context)
                .load(item.imageUrl)
                .placeholder(android.R.drawable.ic_menu_gallery)
                .error(android.R.drawable.ic_menu_report_image)
                .into(binding.ivCartProduct)

            binding.btnIncrease.setOnClickListener { onIncrease(item) }
            binding.btnDecrease.setOnClickListener { onDecrease(item) }
        }
    }

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

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        holder.bind(getItem(position), onIncrease, onDecrease)
    }

    companion object DiffCallback : DiffUtil.ItemCallback<Product>() {
        override fun areItemsTheSame(oldItem: Product, newItem: Product): Boolean =
            oldItem.id == newItem.id

        override fun areContentsTheSame(oldItem: Product, newItem: Product): Boolean =
            oldItem == newItem
    }
}
