package com.aletheia.app.ui.reader

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.aletheia.app.R
import com.aletheia.app.databinding.ItemBookmarkBinding
import com.aletheia.app.model.ReadingBookmark

class BookmarkAdapter(
    private val onBookmarkClicked: (ReadingBookmark) -> Unit,
    private val onDeleteClicked: (ReadingBookmark) -> Unit
) : RecyclerView.Adapter<BookmarkAdapter.BookmarkViewHolder>() {

    private val items = mutableListOf<ReadingBookmark>()

    fun submitList(bookmarks: List<ReadingBookmark>) {
        items.clear()
        items.addAll(bookmarks)
        notifyDataSetChanged()
    }

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

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

    override fun getItemCount(): Int = items.size

    inner class BookmarkViewHolder(
        private val binding: ItemBookmarkBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(item: ReadingBookmark) {
            val context = binding.root.context
            binding.bookmarkTitleText.text = item.label
            binding.bookmarkMetaText.text = context.getString(
                R.string.reader_bookmark_meta,
                item.progressPercent
            )
            binding.root.contentDescription = context.getString(
                R.string.a11y_bookmark_item,
                item.label,
                binding.bookmarkMetaText.text
            )
            binding.deleteBookmarkButton.contentDescription = context.getString(
                R.string.a11y_delete_bookmark,
                item.label
            )
            binding.root.setOnClickListener { onBookmarkClicked(item) }
            binding.deleteBookmarkButton.setOnClickListener { onDeleteClicked(item) }
        }
    }
}
