package com.paperapp.lenscape.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.paperapp.lenscape.R

class FilterAdapter(
    private val tagList: MutableList<TagFilterItem>,
    private val onTagClickListener: (TagFilterItem, Int) -> Unit
): RecyclerView.Adapter<FilterAdapter.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: TagFilterItem, position: Int) {
            tagButton.text = tagItem.name

            // 设置选中状态样式
            if (position == selectedPosition) {
                tagButton.setBackgroundResource(R.drawable.tag_full_bg)
                tagButton.setTextColor(ContextCompat.getColor(itemView.context, R.color.green_1))
            } else {
                tagButton.setBackgroundResource(R.drawable.tag_null_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_each_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<TagFilterItem>) {
        tagList.clear()
        tagList.addAll(newList)
        selectedPosition = 0 // 默认选中第一个
        notifyDataSetChanged()
    }

    fun getSelectedPosition(): Int = selectedPosition
}