package com.example.kasirapp

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.NumberFormat
import java.util.Locale

class CartAdapter(
    private var cartItems: List<MainActivity.CartItem>,
    private val onIncrease: (MainActivity.CartItem) -> Unit,
    private val onDecrease: (MainActivity.CartItem) -> Unit,
    private val onRemove: (MainActivity.CartItem) -> Unit,
    private val onNoteClick: (MainActivity.CartItem) -> Unit
) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    fun updateData(newItems: List<MainActivity.CartItem>) {
        this.cartItems = newItems
        notifyDataSetChanged()
    }

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

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

    override fun getItemCount(): Int = cartItems.size

    inner class CartViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val name: TextView = itemView.findViewById(R.id.tv_cart_item_name)
        private val price: TextView = itemView.findViewById(R.id.tv_cart_item_total_price)
        private val quantity: TextView = itemView.findViewById(R.id.tv_cart_item_quantity)
        private val note: TextView = itemView.findViewById(R.id.tv_cart_item_note)
        private val increaseBtn: ImageButton = itemView.findViewById(R.id.btn_increase_quantity)
        private val decreaseBtn: ImageButton = itemView.findViewById(R.id.btn_decrease_quantity)
        private val removeBtn: ImageButton = itemView.findViewById(R.id.btn_remove_from_cart)
        private val currencyFormat = NumberFormat.getCurrencyInstance(Locale("id", "ID"))

        fun bind(item: MainActivity.CartItem) {
            name.text = item.product.name
            quantity.text = item.quantity.toString()
            price.text = currencyFormat.format((item.product.price * item.quantity).toLong())

            if (item.note.isNullOrBlank()) {
                note.visibility = View.GONE
            } else {
                note.visibility = View.VISIBLE
                note.text = "Catatan: ${item.note}"
            }

            increaseBtn.setOnClickListener { onIncrease(item) }
            decreaseBtn.setOnClickListener { onDecrease(item) }
            removeBtn.setOnClickListener { onRemove(item) }
            itemView.setOnClickListener { onNoteClick(item) }
        }
    }
}