package com.all.pdfreader.pro.app.ui.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.all.pdfreader.pro.app.databinding.AdapterItemBookmarkPageBinding
import com.all.pdfreader.pro.app.room.entity.BookmarkEntity

class BookmarkAdapter(
    private var list: MutableList<BookmarkEntity>,
    private val onItemClick: (BookmarkEntity) -> Unit,
    private val onEditClick: (BookmarkEntity, Int) -> Unit,
    private val onDeleteClick: (BookmarkEntity, Int) -> Unit,
) : RecyclerView.Adapter<BookmarkAdapter.PdfViewHolder>() {

    inner class PdfViewHolder(val binding: AdapterItemBookmarkPageBinding) :
        RecyclerView.ViewHolder(binding.root)

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

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: PdfViewHolder, position: Int) {
        val item = list[position]
        holder.binding.titleTv.text = item.label
        holder.binding.descTv.text = "(#${item.pageNumber + 1})"
        holder.binding.root.setOnClickListener {
            onItemClick(item)
        }
        holder.binding.editBtn.setOnClickListener {
            onEditClick(item, position)
        }
        holder.binding.deleteBtn.setOnClickListener {
            onDeleteClick(item, position)
        }
    }

    override fun getItemCount(): Int = list.size

    @SuppressLint("NotifyDataSetChanged")
    fun updateData(newList: List<BookmarkEntity>) {
        list.clear()
        list.addAll(newList)
        notifyDataSetChanged()
    }

    fun updateItemChanged(updatedBookmark: BookmarkEntity) {
        val index = list.indexOfFirst { it.id == updatedBookmark.id }
        if (index != -1) {
            list = list.toMutableList().apply {
                this[index] = updatedBookmark
            }
            notifyItemChanged(index)
        }
    }

    fun removeItem(position: Int) {
        list.removeAt(position)
        notifyItemRemoved(position)
    }

    fun removeAllItems() {
        val size = list.size
        if (size > 0) {
            list.clear()
            notifyItemRangeRemoved(0, size)
        }
    }
}
