package com.demoscene.tv

import android.content.Intent
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.KeyEvent
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.demoscene.tv.data.DemoDataProvider
import com.demoscene.tv.ui.MarbleButtonHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class HubActivity : FragmentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_hub)

        setupHardcodedButtons()
        loadDynamicCategories()
        applyMarbleTextures()
    }
    
    override fun onResume() {
        super.onResume()
        
        // Check if refresh was requested
        val prefs = getSharedPreferences("demoscene_tv", MODE_PRIVATE)
        if (prefs.getBoolean("refresh_requested", false)) {
            prefs.edit().putBoolean("refresh_requested", false).apply()
            
            // Clear and reload dynamic categories
            val container = findViewById<LinearLayout>(R.id.dynamic_buttons_container)
            container?.removeAllViews()
            loadDynamicCategories()
        }
    }
    
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        val featuredButton = findViewById<LinearLayout>(R.id.hub_featured)
        if ((keyCode == KeyEvent.KEYCODE_DPAD_UP && featuredButton.hasFocus()) || 
            keyCode == KeyEvent.KEYCODE_MENU) {
            startActivity(Intent(this, MenuActivity::class.java))
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun applyMarbleTextures() {
        val buttons = listOf(
            findViewById<LinearLayout>(R.id.hub_top_rated),
            findViewById<LinearLayout>(R.id.hub_recent),
            findViewById<LinearLayout>(R.id.hub_random),
            findViewById<LinearLayout>(R.id.hub_demos),
            findViewById<LinearLayout>(R.id.hub_64k),
            findViewById<LinearLayout>(R.id.hub_4k),
            findViewById<LinearLayout>(R.id.hub_tiny)
        )
        for (button in buttons) {
            button?.let { MarbleButtonHelper.applyRandomMarble(this, it) }
        }
    }

    private fun setupHardcodedButtons() {
        findViewById<LinearLayout>(R.id.hub_featured)?.setOnClickListener { openCategory("Top Rated All Time") }
        findViewById<LinearLayout>(R.id.hub_top_rated)?.setOnClickListener { openCategory("Top Rated All Time") }
        findViewById<LinearLayout>(R.id.hub_recent)?.setOnClickListener { openCategory("Recent Demos") }
        findViewById<LinearLayout>(R.id.hub_random)?.setOnClickListener { openCategory("Random Selection") }
        findViewById<LinearLayout>(R.id.hub_demos)?.setOnClickListener { openCategory("Demos") }
        findViewById<LinearLayout>(R.id.hub_64k)?.setOnClickListener { openCategory("64k Intros") }
        findViewById<LinearLayout>(R.id.hub_4k)?.setOnClickListener { openCategory("4k Intros") }
        findViewById<LinearLayout>(R.id.hub_tiny)?.setOnClickListener { openCategory("256b & Tiny Intros") }
    }

    private fun loadDynamicCategories() {
        CoroutineScope(Dispatchers.Main).launch {
            val categories = withContext(Dispatchers.IO) {
                DemoDataProvider.getCategoryRows(this@HubActivity)
            }
            val hardcodedNames = setOf("Top Rated All Time", "Recent Demos", "Random Selection", "Demos", "64k Intros", "4k Intros", "256b & Tiny Intros")
            val dynamicCategories = categories.filter { !hardcodedNames.contains(it.title) }
            val container = findViewById<LinearLayout>(R.id.dynamic_buttons_container)
            var currentRow: LinearLayout? = null
            var buttonCount = 0
            for (category in dynamicCategories) {
                if (buttonCount % 4 == 0) {
                    currentRow = LinearLayout(this@HubActivity)
                    currentRow.orientation = LinearLayout.HORIZONTAL
                    currentRow.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                    container?.addView(currentRow)
                }
                val button = createCategoryButton(category.title)
                button.setOnClickListener { openCategory(category.title) }
                MarbleButtonHelper.applyRandomMarble(this@HubActivity, button)
                currentRow?.addView(button)
                buttonCount++
            }
        }
    }

    private fun createCategoryButton(title: String): LinearLayout {
        val button = LinearLayout(this)
        val params = LinearLayout.LayoutParams(0, dpToPx(100))
        params.weight = 1f
        params.setMargins(dpToPx(8), dpToPx(8), dpToPx(8), dpToPx(8))
        button.layoutParams = params
        button.orientation = LinearLayout.VERTICAL
        button.gravity = Gravity.CENTER
        button.setPadding(dpToPx(12), dpToPx(12), dpToPx(12), dpToPx(12))
        button.isFocusable = true
        button.isClickable = true
        val icon = TextView(this)
        icon.text = getIconForCategory(title)
        icon.setTextSize(TypedValue.COMPLEX_UNIT_SP, 35f)
        button.addView(icon)
        val titleView = TextView(this)
        titleView.text = title
        titleView.setTextColor(android.graphics.Color.WHITE)
        titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
        titleView.setTypeface(null, android.graphics.Typeface.BOLD)
        val titleParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        titleParams.topMargin = dpToPx(6)
        titleView.layoutParams = titleParams
        button.addView(titleView)
        return button
    }

    private fun getIconForCategory(title: String): String {
        return when {
            title.contains("Windows") -> "🖥️"
            title.contains("Amiga") -> "🖥️"
            title.contains("C64") || title.contains("Commodore") -> "🎮"
            title.contains("MS-Dos") || title.contains("DOS") -> "💾"
            title.matches(Regex("\\d{4}")) -> "📅"
            title.matches(Regex("\\d{4}s")) -> "📆"
            else -> "📁"
        }
    }

    private fun dpToPx(dp: Int): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), resources.displayMetrics).toInt()
    }

    private fun openCategory(categoryName: String) {
        val intent = Intent(this, BrowseGridActivity::class.java)
        intent.putExtra("CATEGORY_FILTER", categoryName)
        startActivity(intent)
    }
}
