package com.aletheia.app.ui.reader

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.aletheia.app.R
import com.aletheia.app.databinding.ItemChapterBinding
import com.aletheia.app.model.ReaderChapterItem

class ChapterAdapter(
    private val onChapterClicked: (ReaderChapterItem) -> Unit
) : RecyclerView.Adapter<ChapterAdapter.ChapterViewHolder>() {

    private val items = mutableListOf<ReaderChapterItem>()

    fun submitList(chapters: List<ReaderChapterItem>) {
        items.clear()
        items.addAll(chapters)
        notifyDataSetChanged()
    }

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

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

    override fun getItemCount(): Int = items.size

    inner class ChapterViewHolder(
        private val binding: ItemChapterBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(item: ReaderChapterItem) {
            val context = binding.root.context
            binding.chapterIndexText.text = item.indexLabel
            binding.chapterLabelText.text = item.label
            binding.chapterCurrentText.visibility = if (item.isCurrent) android.view.View.VISIBLE else android.view.View.GONE
            binding.root.contentDescription = context.getString(
                if (item.isCurrent) R.string.a11y_chapter_item_current else R.string.a11y_chapter_item,
                item.label
            )

            val backgroundColor = if (item.isCurrent) {
                ContextCompat.getColor(context, R.color.surface_strong)
            } else {
                ContextCompat.getColor(context, R.color.surface_color)
            }
            val strokeColor = if (item.isCurrent) {
                ContextCompat.getColor(context, R.color.accent_soft_color)
            } else {
                ContextCompat.getColor(context, R.color.border_color)
            }

            binding.root.setCardBackgroundColor(backgroundColor)
            binding.root.strokeColor = strokeColor
            binding.root.setOnClickListener { onChapterClicked(item) }
        }
    }
}
