package com.photobooth.app

import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView

data class BackgroundOption(
    val id: String,
    val name: String,
    val assetPath: String?
)

class BackgroundOptionAdapter(
    private val items: List<BackgroundOption>,
    private val onBgSelected: (BackgroundOption) -> Unit
) : RecyclerView.Adapter<BackgroundOptionAdapter.ViewHolder>() {

    private var selectedPosition = 0

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val cardBgOption: MaterialCardView = view.findViewById(R.id.cardBgOption)
        val imgBgThumb: ImageView = view.findViewById(R.id.imgBgThumb)
        val txtBgName: TextView = view.findViewById(R.id.txtBgName)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        holder.txtBgName.text = item.name

        if (item.assetPath == null) {
            holder.imgBgThumb.setImageResource(R.drawable.ic_block_white)
        } else {
            try {
                val inputStream = holder.itemView.context.assets.open(item.assetPath)
                val bitmap = BitmapFactory.decodeStream(inputStream)
                holder.imgBgThumb.setImageBitmap(bitmap)
            } catch (e: Exception) {
                holder.imgBgThumb.setImageDrawable(null)
            }
        }

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

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

        holder.itemView.setOnClickListener {
            val previousSelected = selectedPosition
            selectedPosition = position
            notifyItemChanged(previousSelected)
            notifyItemChanged(selectedPosition)
            onBgSelected(item)
        }
    }

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