package melody.offline.music.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import melody.offline.music.App
import melody.offline.music.R
import melody.offline.music.bean.Playlist
import melody.offline.music.databinding.NewPlayListItemBinding
import melody.offline.music.databinding.PlayListItemBinding
import melody.offline.music.media.MediaControllerManager

class NewPlayListAdapter(
    private val context: Context,
    private val list: List<Playlist>,
) : RecyclerView.Adapter<NewPlayListAdapter.ViewHolder>() {

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val bean = list[position]
        holder.bind(bean)

        holder.itemView.setOnClickListener {
            if (itemClickListener != null) {
                itemClickListener?.onItemClick(position)
            }
        }
    }

    override fun getItemCount(): Int = list.size

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

        @OptIn(DelicateCoroutinesApi::class)
        @SuppressLint("SetTextI18n")
        fun bind(bean: Playlist) {

            binding.apply {
                title.text = bean.title
                GlobalScope.launch {
                    val items = App.appPlaylistDBManager.getPlaylistItems(bean.id)
                    withContext(Dispatchers.Main) {
                        name.text = "${items.size} " + context.getString(R.string.songs)
                        if (items.isNotEmpty()) {
                            Glide.with(context).load(items[0].thumbnail).into(image)
                        }
                    }
                }
            }
        }
    }

    private var itemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener) {
        itemClickListener = listener
    }

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }
}