package kr.co.vividnext.sodalive.audio_content.series.content

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.audio_content.series.detail.GetSeriesContentListItem
import kr.co.vividnext.sodalive.databinding.ItemSeriesContentBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

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

    val items = mutableListOf<GetSeriesContentListItem>()

    inner class ViewHolder(
        private val binding: ItemSeriesContentBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: GetSeriesContentListItem) {
            binding.ivCover.load(item.coverImage) {
                crossfade(true)
                placeholder(R.drawable.bg_placeholder)
                transformations(RoundedCornersTransformation(5.3f.dpToPx()))
            }

            binding.tvTitle.text = item.title
            binding.tvDuration.text = item.duration

            binding.tvPrice.visibility = View.GONE
            binding.tvOwned.visibility = View.GONE
            binding.tvRented.visibility = View.GONE
            binding.tvPriceFree.visibility = View.GONE

            if (item.isOwned) {
                binding.tvOwned.visibility = View.VISIBLE
            } else if (item.isRented) {
                binding.tvRented.visibility = View.VISIBLE
            } else if (item.price > 0) {
                binding.tvPrice.text = "${item.price}"
                binding.tvPrice.visibility = View.VISIBLE
            } else {
                binding.tvPriceFree.visibility = View.VISIBLE
            }

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

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

    override fun getItemCount() = items.size

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

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

    fun clear() {
        this.items.clear()
    }
}
