package kr.co.vividnext.sodalive.mypage.profile.tag

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.ItemLiveTagBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

class MemberTagAdapter(
    private val selectedTags: Set<String>,
    private val onItemClick: (String, Boolean) -> Boolean
) : RecyclerView.Adapter<MemberTagAdapter.ViewHolder>() {
    inner class ViewHolder(
        private val binding: ItemLiveTagBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        private var isChecked = false

        fun bind(item: MemberTagResponse) {
            if (selectedTags.contains(item.tag)) {
                binding.ivTagChecked.visibility = View.VISIBLE
                binding.ivTag.setBackgroundResource(R.drawable.bg_round_corner_30_3bb9f1)
                isChecked = true
            } else {
                binding.ivTagChecked.visibility = View.GONE
                binding.ivTag.background = null
                isChecked = false
            }

            binding.ivTag.load(item.image) {
                crossfade(true)
                placeholder(R.drawable.bg_placeholder)
                transformations(RoundedCornersTransformation(30f.dpToPx()))
            }
            binding.tvTag.text = item.tag

            binding.root.setOnClickListener {
                isChecked = !isChecked

                if (onItemClick(item.tag, isChecked)) {
                    if (isChecked) {
                        binding.ivTagChecked.visibility = View.VISIBLE
                        binding.ivTag.setBackgroundResource(R.drawable.bg_round_corner_30_3bb9f1)
                    } else {
                        binding.ivTagChecked.visibility = View.GONE
                        binding.ivTag.background = null
                    }
                } else {
                    isChecked = !isChecked
                }
            }
        }
    }

    val items = mutableSetOf<MemberTagResponse>()

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

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

    override fun getItemCount() = items.size
}
