package com.example.bnsptest.ui

import android.R
import android.view.LayoutInflater
import android.view.View
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.ItemProductBinding

class ProductAdapter(
    private val showAddToCart: Boolean = true,
    private val onAddToCart: (Product) -> Unit = {}
) : ListAdapter<Product, ProductAdapter.ProductViewHolder>(DiffCallback) {

    class ProductViewHolder(private val binding: ItemProductBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(product: Product, showAddToCart: Boolean, onAddToCart: (Product) -> Unit) {
            binding.tvProductName.text = product.name
            binding.tvProductPrice.text = "Rp${product.price}"

            Glide.with(binding.ivProduct.context)
                .load(product.imageUrl)
                .placeholder(R.drawable.ic_menu_gallery)
                .error(R.drawable.ic_menu_report_image)
                .into(binding.ivProduct)

            binding.btnAddToCart.visibility = if (showAddToCart) View.VISIBLE else View.GONE
            binding.btnAddToCart.setOnClickListener { onAddToCart(product) }
        }
    }

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

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        holder.bind(getItem(position), showAddToCart, onAddToCart)
    }

    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
    }
}