package kr.co.vividnext.sodalive.audio_content.playlist

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.RoundedCornersTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.databinding.ItemPlaylistListBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

class AudioContentPlaylistListAdapter(
    private val onClickItem: (Long) -> Unit
) : RecyclerView.Adapter<AudioContentPlaylistListAdapter.ViewHolder>() {

    private val items = mutableListOf<GetPlaylistsItem>()

    inner class ViewHolder(
        private val binding: ItemPlaylistListBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("SetTextI18n")
        fun bind(item: GetPlaylistsItem) {
            binding.ivCover.load(item.coverImageUrl) {
                crossfade(true)
                placeholder(R.drawable.bg_placeholder)
                transformations(RoundedCornersTransformation(5.3f.dpToPx()))
            }

            binding.tvTitle.text = item.title
            binding.tvContentCount.text = "총 ${item.contentCount}개"

            if (item.desc.isNotBlank()) {
                binding.tvDesc.text = item.desc
                binding.tvDesc.visibility = View.VISIBLE
            } else {
                binding.tvDesc.visibility = View.GONE
            }

            binding.root.setOnClickListener { onClickItem(item.id) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
        ItemPlaylistListBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
    )

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

    override fun getItemCount() = items.count()

    @SuppressLint("NotifyDataSetChanged")
    fun updateItems(items: List<GetPlaylistsItem>) {
        this.items.clear()
        this.items.addAll(items)
        notifyDataSetChanged()
    }
}
