package com.example.orderly.ui.cart

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.orderly.R
import com.example.orderly.data.entity.CartItem
import com.example.orderly.databinding.ItemCartBinding
import java.text.NumberFormat
import java.util.*

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

    class CartViewHolder(private val binding: ItemCartBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(
            cartItem: CartItem,
            onIncrease: (CartItem) -> Unit,
            onDecrease: (CartItem) -> Unit
        ) {
            binding.tvCartProductName.text = cartItem.productName
            
            val formatter = NumberFormat.getCurrencyInstance(Locale("id", "ID"))
            binding.tvCartProductPrice.text = formatter.format(cartItem.productPrice)
            binding.tvQuantity.text = cartItem.quantity.toString()
            
            // Kita hapus logo dari error() agar tidak membingungkan
            Glide.with(binding.ivCartProduct.context)
                .load(cartItem.imageUrl)
                .placeholder(android.R.drawable.ic_menu_gallery) // Pakai icon gallery bawaan aja buat loading
                .error(android.R.drawable.stat_notify_error)     // Pakai icon error bawaan kalau gagal
                .into(binding.ivCartProduct)
                
            binding.btnIncrease.setOnClickListener { onIncrease(cartItem) }
            binding.btnDecrease.setOnClickListener { onDecrease(cartItem) }
        }
    }

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

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

    companion object DiffCallback : DiffUtil.ItemCallback<CartItem>() {
        override fun areItemsTheSame(oldItem: CartItem, newItem: CartItem): Boolean {
            return oldItem.cartId == newItem.cartId
        }
        override fun areContentsTheSame(oldItem: CartItem, newItem: CartItem): Boolean {
            return oldItem == newItem
        }
    }
}
