package com.demoscene.tv.ui

import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.demoscene.tv.R
import com.demoscene.tv.model.Demo

class DemoGridAdapter(
    private val demos: List<Demo>,
    private val onDemoClick: (Demo) -> Unit
) : RecyclerView.Adapter<DemoGridAdapter.DemoViewHolder>() {

    private val marbleDrawables = listOf(
        R.drawable.marble_1,
        R.drawable.marble_2,
        R.drawable.marble_3,
        R.drawable.marble_4,
        R.drawable.marble_5,
        R.drawable.marble_6,
        R.drawable.marble_7,
        R.drawable.marble_8,
        R.drawable.marble_9,
        R.drawable.marble_10
    )

    class DemoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val container: FrameLayout = view as FrameLayout
        val thumbnail: ImageView = view.findViewById(R.id.demo_thumbnail)
        val title: TextView = view.findViewById(R.id.demo_title)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DemoViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_demo_card, parent, false)
        
        // Calculate width for 5 cards across with spacing
        val screenWidth = parent.context.resources.displayMetrics.widthPixels
        val paddingDp = 80
        val spacingDp = 16
        val density = parent.context.resources.displayMetrics.density
        val totalPadding = (paddingDp * density).toInt()
        val totalSpacing = (spacingDp * 6 * density).toInt()
        val availableWidth = screenWidth - totalPadding - totalSpacing
        val cardWidth = availableWidth / 5
        
        // Fixed height like Hero buttons
        val cardHeight = (100 * density).toInt()
        
        val params = view.layoutParams as RecyclerView.LayoutParams
        params.width = cardWidth
        params.height = cardHeight
        params.setMargins((8 * density).toInt(), (8 * density).toInt(), (8 * density).toInt(), (8 * density).toInt())
        view.layoutParams = params
        
        return DemoViewHolder(view)
    }

    override fun onBindViewHolder(holder: DemoViewHolder, position: Int) {
        val demo = demos[position]
        val context = holder.itemView.context
        
        holder.title.text = demo.title
        
        // Apply random marble as background (fallback if no screenshot)
        val randomMarble = marbleDrawables.random()
        applyMarbleBackground(holder.container, randomMarble, false)
        
        // Load thumbnail - if it loads, it covers the marble
        Glide.with(context)
            .load(demo.thumbnailUrl)
            .centerCrop()
            .into(holder.thumbnail)
        
        holder.container.setOnClickListener {
            onDemoClick(demo)
        }
        
        holder.container.setOnFocusChangeListener { view, hasFocus ->
            applyMarbleBackground(view as FrameLayout, randomMarble, hasFocus)
            if (hasFocus) {
                view.animate().scaleX(1.08f).scaleY(1.08f).setDuration(100).start()
            } else {
                view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(100).start()
            }
        }
    }
    
    private fun applyMarbleBackground(view: FrameLayout, marbleRes: Int, focused: Boolean) {
        val context = view.context
        val marbleDrawable = ContextCompat.getDrawable(context, marbleRes)?.mutate()
        
        val borderDrawable = GradientDrawable()
        borderDrawable.shape = GradientDrawable.RECTANGLE
        borderDrawable.cornerRadius = 12f
        if (focused) {
            borderDrawable.setStroke(6, 0xFFFFFFFF.toInt())
        } else {
            borderDrawable.setStroke(2, 0x66FFFFFF.toInt())
        }
        
        val layers = arrayOf(marbleDrawable, borderDrawable)
        view.background = LayerDrawable(layers)
    }

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