package com.photobooth.app

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView

enum class EditAttribute {
    BRIGHTNESS, CONTRAST, SATURATION, VIBRANCE, TEMPERATURE, TINT,        // Nhóm 1: Cơ bản
    CLARITY, DEHAZE, VIGNETTE_AMOUNT,                                    // Nhóm 2: Nâng cao
    FADED_BLACK_LEVEL, SHADOWS_TINT_R, SHADOWS_TINT_G, SHADOWS_TINT_B,   // Nhóm 3: Tone Curve
    GRAIN_AMOUNT, GRAIN_SIZE,                                            // Nhóm 4: Nhiễu hạt
    PORTRAIT_BLUR, BG_REPLACE                                            // Nhóm 5: Tách nền AI
}

data class AttributeNode(
    val type: EditAttribute,
    val displayName: String,
    val iconResId: Int
)

class AttributeAdapter(
    private val items: List<AttributeNode>,
    private val onItemSelected: (AttributeNode) -> Unit
) : RecyclerView.Adapter<AttributeAdapter.ViewHolder>() {

    var selectedPosition = 0
        set(value) {
            val old = field
            field = value
            notifyItemChanged(old)
            notifyItemChanged(value)
        }

    fun updateSelection(selectedType: EditAttribute) {
        val index = items.indexOfFirst { it.type == selectedType }
        if (index != -1) {
            selectedPosition = index
        }
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val imgIcon: ImageView = view.findViewById(R.id.imgAttributeIcon)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        holder.imgIcon.setImageResource(item.iconResId)

        // If selected, color is orange, else white
        if (position == selectedPosition) {
            holder.imgIcon.setColorFilter(Color.parseColor("#FF9800"))
        } else {
            // Keep original vector coloring if it is colored droplet, else white tint
            if (item.type == EditAttribute.SHADOWS_TINT_R ||
                item.type == EditAttribute.SHADOWS_TINT_G ||
                item.type == EditAttribute.SHADOWS_TINT_B) {
                holder.imgIcon.clearColorFilter()
            } else {
                holder.imgIcon.setColorFilter(Color.parseColor("#FFFFFF"))
            }
        }

        holder.itemView.setOnClickListener {
            selectedPosition = holder.adapterPosition
            onItemSelected(item)
        }
    }

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