package com.example.defenseapplication.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.ItemAddLinkedUserBinding

data class UserItem(val name: String, val phone: String, val userId: String = "")

class AddLinkedUserAdapter(
    private val data: List<UserItem>,
    private val selectedIds: MutableSet<String>,
    private val selectedUserIdMap: MutableMap<String, String>,
    private val onItemClick: (String, Boolean, String?) -> Unit
) : RecyclerView.Adapter<AddLinkedUserAdapter.ViewHolder>() {

    inner class ViewHolder(val binding: ItemAddLinkedUserBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: UserItem) {
            binding.tvUserName.text = "${item.name}-${item.phone}"
            val isChecked = selectedIds.contains(item.phone)
            binding.cbSelect.isChecked = isChecked
            binding.cbSelect.setOnCheckedChangeListener { _, checked ->
                if (checked) {
                    binding.cbSelect.buttonTintList = android.content.res.ColorStateList.valueOf(Color.parseColor("#09C2BD"))
                } else {
                    binding.cbSelect.buttonTintList = null
                }
                onItemClick(item.phone, checked, item.userId)
            }
            if (isChecked) {
                binding.cbSelect.buttonTintList = android.content.res.ColorStateList.valueOf(Color.parseColor("#09C2BD"))
            }
        }
    }

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

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

    override fun getItemCount(): Int = data.size
}