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.ItemReadingNoteBinding
import com.aletheia.app.model.ReadingNote

class ReadingNoteAdapter(
    private val onNoteClicked: (ReadingNote) -> Unit,
    private val onDeleteClicked: (ReadingNote) -> Unit
) : RecyclerView.Adapter<ReadingNoteAdapter.ViewHolder>() {
    private val notes = mutableListOf<ReadingNote>()

    fun submitList(items: List<ReadingNote>) {
        notes.clear()
        notes.addAll(items)
        notifyDataSetChanged()
    }

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

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

    override fun getItemCount(): Int = notes.size

    inner class ViewHolder(private val binding: ItemReadingNoteBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(note: ReadingNote) {
            val context = binding.root.context
            binding.noteQuoteText.text = note.selectedText?.takeIf { it.isNotBlank() }
                ?: context.getString(R.string.reader_note_position_only)
            binding.noteBodyText.text = note.noteText
            binding.noteMetaText.text = context.getString(R.string.reader_bookmark_meta, note.progressPercent)
            binding.root.contentDescription = context.getString(
                R.string.a11y_note_item,
                binding.noteQuoteText.text,
                binding.noteMetaText.text
            )
            binding.deleteNoteButton.contentDescription = context.getString(R.string.a11y_delete_note)
            binding.root.setOnClickListener { onNoteClicked(note) }
            binding.deleteNoteButton.setOnClickListener { onDeleteClicked(note) }
        }
    }
}
