package com.photobooth.app

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView

class PresetAdapter(
    private var presets: List<ColorPreset>,
    private val onPresetSelected: (ColorPreset) -> Unit,
    private val onEditClicked: (ColorPreset) -> Unit
) : RecyclerView.Adapter<PresetAdapter.ViewHolder>() {

    private var selectedPosition = 0

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val cardPreset: MaterialCardView = view.findViewById(R.id.cardPreset)
        val viewPresetColor: View = view.findViewById(R.id.viewPresetColor)
        val txtPresetName: TextView = view.findViewById(R.id.txtPresetName)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val preset = presets[position]
        holder.txtPresetName.text = preset.name

        // Draw preview circle or block icon
        if (preset.id == "DEFAULT") {
            holder.viewPresetColor.setBackgroundResource(R.drawable.ic_block_white)
            holder.txtPresetName.text = holder.itemView.context.getString(R.string.default_frame)
        } else {
            val colorHex = when (preset.id) {
                "instax_faded_warm_01" -> "#FFF57C00"
                "instax_bw_cool" -> "#FF808080"
                "instax_cool_summer" -> "#FF00BCD4"
                else -> "#FF9E9E9E"
            }
            val circleDrawable = GradientDrawable().apply {
                shape = GradientDrawable.OVAL
                setColor(Color.parseColor(colorHex))
            }
            holder.viewPresetColor.background = circleDrawable
        }

        // Highlight selection
        val strokeWidthPx = (3 * holder.itemView.context.resources.displayMetrics.density).toInt()
        if (position == selectedPosition) {
            holder.cardPreset.strokeColor = ContextCompat.getColor(holder.itemView.context, R.color.theme_primary)
            holder.cardPreset.strokeWidth = strokeWidthPx
        } else {
            holder.cardPreset.strokeColor = ContextCompat.getColor(holder.itemView.context, R.color.theme_transparent)
            holder.cardPreset.strokeWidth = 0
        }

        // Setup custom 1-second long press detector with touch slop cancellation
        val handler = android.os.Handler(android.os.Looper.getMainLooper())
        var isLongPressTriggered = false
        var startX = 0f
        var startY = 0f
        val touchSlop = 15f // pixels

        val longPressRunnable = Runnable {
            if (preset.isEditable) {
                isLongPressTriggered = true
                holder.itemView.performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS)
                onEditClicked(preset)
            }
        }

        holder.itemView.setOnTouchListener { view, event ->
            when (event.action) {
                android.view.MotionEvent.ACTION_DOWN -> {
                    isLongPressTriggered = false
                    startX = event.x
                    startY = event.y
                    handler.postDelayed(longPressRunnable, 800)
                }
                android.view.MotionEvent.ACTION_MOVE -> {
                    if (Math.abs(event.x - startX) > touchSlop || Math.abs(event.y - startY) > touchSlop) {
                        handler.removeCallbacks(longPressRunnable)
                    }
                }
                android.view.MotionEvent.ACTION_UP -> {
                    handler.removeCallbacks(longPressRunnable)
                    if (!isLongPressTriggered) {
                        val previousSelected = selectedPosition
                        selectedPosition = holder.adapterPosition
                        if (selectedPosition != RecyclerView.NO_POSITION) {
                            notifyItemChanged(previousSelected)
                            notifyItemChanged(selectedPosition)
                            onPresetSelected(preset)
                            view.performClick()
                        }
                    }
                }
                android.view.MotionEvent.ACTION_CANCEL -> {
                    handler.removeCallbacks(longPressRunnable)
                }
            }
            true
        }
    }

    override fun getItemCount(): Int = presets.size
    
    fun updatePresets(newPresets: List<ColorPreset>) {
        this.presets = newPresets
        notifyDataSetChanged()
    }

    fun resetSelection() {
        val previousSelected = selectedPosition
        selectedPosition = 0
        notifyItemChanged(previousSelected)
        notifyItemChanged(selectedPosition)
    }
}
