package com.rugvedsarika.cashcounter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.rugvedsarika.cashcounter.data.HistoryEntity
import java.text.NumberFormat
import java.util.Locale

class HistoryAdapter(private val onDelete: (HistoryEntity) -> Unit) :
    ListAdapter<HistoryEntity, HistoryAdapter.HistoryViewHolder>(HistoryDiffCallback()) {

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


    
    // Fix for type mismatch if I used generic ViewHolder
    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class HistoryViewHolder(itemView: View, private val onDelete: (HistoryEntity) -> Unit) :
        RecyclerView.ViewHolder(itemView) {
        
        private val tvDate: TextView = itemView.findViewById(R.id.tvDate)
        private val tvTotalAmount: TextView = itemView.findViewById(R.id.tvTotalAmount)
        private val tvRemarks: TextView = itemView.findViewById(R.id.tvRemarks)
        private val tvBreakdown: TextView = itemView.findViewById(R.id.tvBreakdown)
        private val btnDelete: ImageButton = itemView.findViewById(R.id.btnDelete)

        fun bind(item: HistoryEntity) {
            tvDate.text = item.getFormattedDate()
            tvTotalAmount.text = NumberFormat.getCurrencyInstance(Locale.forLanguageTag("en-IN")).format(item.totalAmount)
            
            if (!item.remarks.isNullOrEmpty()) {
                tvRemarks.text = item.remarks
                tvRemarks.visibility = View.VISIBLE
            } else {
                tvRemarks.visibility = View.GONE
            }
            
            tvBreakdown.text = item.breakdown
            
            btnDelete.setOnClickListener {
                onDelete(item)
            }
        }
    }

    class HistoryDiffCallback : DiffUtil.ItemCallback<HistoryEntity>() {
        override fun areItemsTheSame(oldItem: HistoryEntity, newItem: HistoryEntity): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: HistoryEntity, newItem: HistoryEntity): Boolean {
            return oldItem == newItem
        }
    }
}
