package com.example.kasirapp

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.kasirapp.data.Product

class ProductAdapter(
    private var productList: List<Product>,
    private val onAddClick: (Product) -> Unit
) : RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_product_card, parent, false)
        return ProductViewHolder(view)
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        holder.bind(productList[position])
    }

    override fun getItemCount(): Int = productList.size

    fun updateProducts(newProducts: List<Product>) {
        this.productList = newProducts
        notifyDataSetChanged()
    }

    inner class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val nameTextView: TextView = itemView.findViewById(R.id.tv_product_name)
        private val priceTextView: TextView = itemView.findViewById(R.id.tv_product_price)
        private val stockTextView: TextView = itemView.findViewById(R.id.tv_product_stock)
        private val imageView: ImageView = itemView.findViewById(R.id.iv_product_image)
        private val addButton: Button = itemView.findViewById(R.id.btn_add_to_cart)

        fun bind(product: Product) {
            nameTextView.text = product.name
            priceTextView.text = "Rp ${product.price}"
            stockTextView.text = "Stok: ${product.stock}"
            
            val imageResId = itemView.context.resources.getIdentifier(product.imageResName, "drawable", itemView.context.packageName)
            if (imageResId != 0) {
                imageView.setImageResource(imageResId)
            } else {
                imageView.setImageResource(R.drawable.ic_launcher_background) // Fallback image
            }

            addButton.isEnabled = product.stock > 0
            addButton.text = if (product.stock > 0) "Tambah" else "Habis"
            addButton.setOnClickListener { onAddClick(product) }
        }
    }
}
