package kr.co.vividnext.sodalive.audio_content.category

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.databinding.ItemContentCategoryBinding

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

    private val items = mutableListOf<GetCategoryListResponse>()
    private var selectedCategory = ""

    inner class ViewHolder(
        private val context: Context,
        private val binding: ItemContentCategoryBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("NotifyDataSetChanged")
        fun bind(item: GetCategoryListResponse) {
            if (
                item.category == selectedCategory ||
                (selectedCategory == "" && item.category == "전체")
            ) {
                binding.tvCategory.setBackgroundResource(
                    R.drawable.bg_round_corner_16_7_transparent_3bb9f1
                )
                binding.tvCategory.setTextColor(
                    ContextCompat.getColor(context, R.color.color_3bb9f1)
                )
            } else {
                binding.tvCategory.setBackgroundResource(
                    R.drawable.bg_round_corner_16_7_transparent_777777
                )
                binding.tvCategory.setTextColor(
                    ContextCompat.getColor(context, R.color.color_777777)
                )
            }

            binding.tvCategory.text = item.category
            binding.root.setOnClickListener {
                onClick(item.categoryId)
                selectedCategory = item.category
                notifyDataSetChanged()
            }
        }
    }

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

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

    override fun getItemCount() = items.size

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

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