package com.example.defenseapplication.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.ItemLinkedUserBinding

data class LinkedUser(
    val userId: String,
    val name: String,
    val phone: String,
    val idCard: String,
    val time: String
)

class LinkedUserAdapter(
    private val isUnlinkMode: Boolean,
    private val onItemClick: (LinkedUser, Int) -> Unit
) : RecyclerView.Adapter<LinkedUserAdapter.LinkedUserViewHolder>() {

    private val items = mutableListOf<LinkedUser>()

    fun submitList(userList: List<LinkedUser>) {
        items.clear()
        items.addAll(userList)
        notifyDataSetChanged()
    }

    fun removeItem(position: Int) {
        if (position in items.indices) {
            items.removeAt(position)
            notifyItemRemoved(position)
        }
    }

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

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

    override fun getItemCount(): Int = items.size

    inner class LinkedUserViewHolder(
        val binding: ItemLinkedUserBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(item: LinkedUser, position: Int) {
            val context = binding.root.context
            binding.tvUserName.text = item.name
            binding.tvTime.text = item.time
            binding.tvPhone.text = context.getString(R.string.linked_user_phone_label, item.phone)
            binding.tvIdCard.text = context.getString(R.string.linked_user_idcard_label, item.idCard)

            binding.root.setOnClickListener {
                onItemClick(item, position)
            }
        }
    }
}
