package kr.co.vividnext.sodalive.following

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.CircleCropTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.databinding.ItemFollowerListBinding

class FollowingCreatorAdapter(
    private val onClickItem: (Long) -> Unit,
    private val onClickFollow: (Long, Boolean) -> Unit
) : RecyclerView.Adapter<FollowingCreatorAdapter.ViewHolder>() {

    private val items = mutableListOf<GetCreatorFollowingAllListItem>()

    inner class ViewHolder(
        private val binding: ItemFollowerListBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("NotifyDataSetChanged")
        fun bind(item: GetCreatorFollowingAllListItem) {
            binding.tvNickname.text = item.nickname
            binding.ivProfile.load(item.profileImageUrl) {
                transformations(CircleCropTransformation())
                placeholder(R.drawable.bg_placeholder)
                crossfade(true)
            }

            binding.ivFollow.visibility = View.VISIBLE
            if (item.isFollow) {
                binding.ivFollow.setImageResource(
                    if (item.isNotify) {
                        R.drawable.btn_following_big
                    } else {
                        R.drawable.btn_following_no_alarm_big
                    }
                )
            } else {
                binding.ivFollow.setImageResource(R.drawable.btn_follow_big)
            }

            binding.ivFollow.setOnClickListener {
                onClickFollow(item.creatorId, item.isFollow)
            }
            binding.root.setOnClickListener { onClickItem(item.creatorId) }
        }
    }

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

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

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

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

    override fun getItemCount() = items.size
}
