package com.amz.genie.adapters

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 com.amz.genie.R
import com.amz.genie.models.ActivityItem

class ActivityAdapter(
    private val onDelete: (Int) -> Unit
) : RecyclerView.Adapter<ActivityAdapter.VH>() {

    private val items = mutableListOf<ActivityItem>()

    fun submitList(newItems: List<ActivityItem>) {
        items.clear()
        items.addAll(newItems)
        notifyDataSetChanged()
    }

    fun addItem(item: ActivityItem) {
        items.add(item)
        notifyItemInserted(items.lastIndex)
    }

    fun removeAt(position: Int) {
        if (position < 0 || position >= items.size) return
        items.removeAt(position)
        notifyItemRemoved(position)
    }

    fun getItems(): List<ActivityItem> = items.toList()

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

    override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(items[position], position)

    override fun getItemCount(): Int = items.size

    inner class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tv = itemView.findViewById<TextView>(R.id.tv_activity)
        private val btnDelete = itemView.findViewById<ImageButton>(R.id.btn_delete_activity)

        fun bind(item: ActivityItem, pos: Int) {
            tv.text = item.text
            btnDelete.setOnClickListener { onDelete(pos) }
        }
    }
}