package kr.co.vividnext.sodalive.audio_content.main.ranking

import android.annotation.SuppressLint
import android.view.LayoutInflater
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.audio_content.main.GetAudioContentRankingItem
import kr.co.vividnext.sodalive.databinding.ItemAudioContentMainRankingBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

class AudioContentMainRankingAdapter(
    private val width: Int,
    private val onClickItem: (Long) -> Unit
) : RecyclerView.Adapter<AudioContentMainRankingAdapter.AudioContentMainRankingItemViewHolder>() {

    inner class AudioContentMainRankingItemViewHolder(
        private val binding: ItemAudioContentMainRankingBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("SetTextI18n")
        fun bind(item: GetAudioContentRankingItem, index: Int) {
            val lp = binding.root.layoutParams
            lp.width = width
            binding.root.layoutParams = lp

            binding.root.setOnClickListener { onClickItem(item.contentId) }
            binding.tvTitle.text = item.title
            binding.tvRank.text = "${index + 1}"
            binding.tvNickname.text = item.creatorNickname

            binding.ivCover.load(item.coverImageUrl) {
                crossfade(true)
                placeholder(R.drawable.ic_place_holder)
                transformations(RoundedCornersTransformation(2.7f.dpToPx()))
            }
        }
    }

    private val items = mutableListOf<GetAudioContentRankingItem>()

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

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

    override fun getItemCount() = items.size

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