package com.photobooth.app

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.google.android.material.card.MaterialCardView

class FrameStackAdapter(
    private val stacks: List<FrameStack>,
    private val onStackSelected: (FrameStack, Int) -> Unit
) : RecyclerView.Adapter<FrameStackAdapter.ViewHolder>() {

    private var selectedPosition = -1

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val cardStack: MaterialCardView = view.findViewById(R.id.cardStack)
        val txtStackName: TextView = view.findViewById(R.id.txtStackName)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val stack = stacks[position]
        holder.txtStackName.text = stack.themeName

        val strokeWidthPx = (3 * holder.itemView.context.resources.displayMetrics.density).toInt()

        if (position == selectedPosition) {
            holder.cardStack.strokeColor = ContextCompat.getColor(holder.itemView.context, R.color.theme_red_stroke)
            holder.cardStack.strokeWidth = strokeWidthPx
        } else {
            holder.cardStack.strokeColor = ContextCompat.getColor(holder.itemView.context, R.color.theme_transparent)
            holder.cardStack.strokeWidth = 0
        }

        holder.itemView.setOnClickListener {
            val previousSelected = selectedPosition
            selectedPosition = if (selectedPosition == position) {
                -1 // Toggle collapse if clicked again
            } else {
                position
            }
            notifyItemChanged(previousSelected)
            notifyItemChanged(selectedPosition)
            onStackSelected(stack, selectedPosition)
        }
    }

    override fun getItemCount(): Int = stacks.size
    
    fun clearSelection() {
        val previousSelected = selectedPosition
        selectedPosition = -1
        if (previousSelected != -1) {
            notifyItemChanged(previousSelected)
        }
    }
}
