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.ProdukEntity
import com.example.tabbuy.databinding.ItemProdukBinding
import java.text.NumberFormat
import java.util.Locale

class ProdukAdapter(
    private val onProductClick: (ProdukEntity) -> Unit,
    private val onAddToCart: (ProdukEntity) -> Unit,
    private val onEditClick: (ProdukEntity) -> Unit,
    private val onDeleteClick: (ProdukEntity) -> Unit
) : RecyclerView.Adapter<ProdukAdapter.ProdukViewHolder>() {

    private var produkList = emptyList<ProdukEntity>()

    class ProdukViewHolder(val binding: ItemProdukBinding) : RecyclerView.ViewHolder(binding.root)

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

    override fun onBindViewHolder(holder: ProdukViewHolder, position: Int) {
        val currentProduk = produkList[position]
        holder.binding.tvNamaProduk.text = currentProduk.nama
        
        // Format Mata Uang
        val localeID = Locale("in", "ID")
        val formatRupiah = NumberFormat.getCurrencyInstance(localeID)
        formatRupiah.maximumFractionDigits = 0
        holder.binding.tvHargaProduk.text = formatRupiah.format(currentProduk.harga)
        
        holder.binding.tvDeskripsiProduk.text = currentProduk.deskripsi
        
        // Menampilkan Rating
        holder.binding.tvRatingKatalog.text = currentProduk.rating.toString()
        
        Glide.with(holder.itemView.context)
            .load(currentProduk.gambar)
            .placeholder(android.R.drawable.ic_menu_gallery)
            .error(android.R.drawable.ic_menu_report_image)
            .into(holder.binding.ivProduk)
        
        holder.itemView.setOnClickListener {
            onProductClick(currentProduk)
        }

        holder.binding.btnTambahKeranjang.setOnClickListener {
            onAddToCart(currentProduk)
        }

        holder.binding.btnEdit.setOnClickListener {
            onEditClick(currentProduk)
        }

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

    override fun getItemCount() = produkList.size

    fun setData(produk: List<ProdukEntity>) {
        this.produkList = produk
        notifyDataSetChanged()
    }
}
