package com.design.zenspace.tools

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.design.zenspace.R

class TagAdapter(
    private val tagList: MutableList<TagItem>,
    private val onTagClickListener: (TagItem, Int) -> Unit
): RecyclerView.Adapter<TagAdapter.TagViewHolder>()  {
    private var selectedPosition = 0

    inner class TagViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tagButton: TextView = itemView.findViewById(R.id.tv_tag)

        fun bind(tagItem: TagItem, position: Int) {
            tagButton.text = tagItem.name

            // 设置选中状态样式
            if (position == selectedPosition) {
                tagButton.setBackgroundResource(R.drawable.tag_selected_bg)
                tagButton.setTextColor(ContextCompat.getColor(itemView.context, R.color.white))
            } else {
                tagButton.setBackgroundResource(R.drawable.tag_normal_bg)
                tagButton.setTextColor(ContextCompat.getColor(itemView.context, R.color.black))
            }

            // 点击事件
            tagButton.setOnClickListener {
                if (selectedPosition != position) {
                    // 更新之前选中的item
                    val previousPosition = selectedPosition
                    selectedPosition = position
                    notifyItemChanged(previousPosition)
                    notifyItemChanged(position)

                    onTagClickListener(tagItem, position)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TagViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_tag, parent, false)
        return TagViewHolder(view)
    }

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

    override fun getItemCount(): Int = tagList.size

    fun setData(newList: List<TagItem>) {
        tagList.clear()
        tagList.addAll(newList)
        selectedPosition = 0 // 默认选中第一个
        notifyDataSetChanged()
    }

    fun getSelectedPosition(): Int = selectedPosition
}