package com.example.defenseapplication.adapter

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

class FamilyAdapter(
    private val onItemClick: (String) -> Unit
) : RecyclerView.Adapter<FamilyAdapter.FamilyViewHolder>() {

    private val items = mutableListOf<String>()
    private var selectedFamily: String? = null

    fun submitList(familyList: List<String>, currentFamily: String) {
        items.clear()
        items.addAll(familyList)
        selectedFamily = currentFamily
        notifyDataSetChanged()
    }

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

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

    override fun getItemCount(): Int = items.size

    inner class FamilyViewHolder(private val binding: ItemFamilyBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: String) {
            binding.tvFamilyName.text = item
            val textColor = if (item == selectedFamily) R.color.green else R.color.black
            binding.tvFamilyName.setTextColor(binding.root.context.getColor(textColor))
            binding.root.setOnClickListener { onItemClick(item) }
        }
    }
}