package com.example.orderly.ui.catalog

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

class ProductAdapter(
    private val onDeleteClick: (Product) -> Unit,
    private val onItemClick: (Product) -> Unit,
) : ListAdapter<Product, ProductAdapter.ProductViewHolder>(DiffCallback) {

    class ProductViewHolder(private val binding: ItemProductBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(
            product: Product,
            onDeleteClick: (Product) -> Unit,
            onItemClick: (Product) -> Unit,
        ) {
            binding.tvProductName.text = product.name

            val formatter = NumberFormat.getCurrencyInstance(Locale("id", "ID"))
            binding.tvProductPrice.text = formatter.format(product.price)

            Glide.with(binding.ivProduct.context)
                .load(product.imageUrl)
                .into(binding.ivProduct)

            binding.root.setOnClickListener { onItemClick(product) }

            binding.btnDelete.setOnClickListener { onDeleteClick(product) }

        }
    }

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

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

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

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