package com.demoscene.tv

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.demoscene.tv.data.DemoDataProvider
import com.demoscene.tv.ui.DemoGridAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import android.graphics.Rect
import android.view.View

class BrowseGridActivity : FragmentActivity() {

    private lateinit var recyclerView: RecyclerView

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

        recyclerView = findViewById(R.id.demos_grid)
        val titleView = findViewById<TextView>(R.id.category_title)

        recyclerView.layoutManager = GridLayoutManager(this, 5)

        val spacing = (8 * resources.displayMetrics.density).toInt()
        recyclerView.addItemDecoration(GridSpacingDecoration(5, spacing))

        val searchGroup = intent.getStringExtra("SEARCH_GROUP")
        val categoryFilter = intent.getStringExtra("CATEGORY_FILTER")
        
        if (searchGroup != null) {
            loadDemosByGroup(searchGroup, recyclerView, titleView)
        } else if (categoryFilter != null) {
            loadDemosByCategory(categoryFilter, recyclerView, titleView)
        }
    }
    
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // UP at top of list shows menu
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            val layoutManager = recyclerView.layoutManager as? GridLayoutManager
            val firstVisible = layoutManager?.findFirstCompletelyVisibleItemPosition() ?: 0
            // If we're at the top row (first 5 items), show menu
            if (firstVisible < 5) {
                startActivity(Intent(this, MenuActivity::class.java))
                return true
            }
        }
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            startActivity(Intent(this, MenuActivity::class.java))
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
    
    private fun loadDemosByGroup(groupName: String, recyclerView: RecyclerView, titleView: TextView) {
        titleView.text = "More by $groupName"
        
        CoroutineScope(Dispatchers.Main).launch {
            val demos = withContext(Dispatchers.IO) {
                DemoDataProvider.searchByGroup(this@BrowseGridActivity, groupName)
            }
            
            val adapter = DemoGridAdapter(demos) { demo ->
                val intent = Intent(this@BrowseGridActivity, DemoDetailsActivity::class.java)
                intent.putExtra("demo", demo)
                startActivity(intent)
            }
            recyclerView.adapter = adapter
        }
    }

    private fun loadDemosByCategory(categoryName: String, recyclerView: RecyclerView, titleView: TextView) {
        titleView.text = categoryName

        CoroutineScope(Dispatchers.Main).launch {
            val categories = withContext(Dispatchers.IO) {
                DemoDataProvider.getCategoryRows(this@BrowseGridActivity)
            }

            val demos = categories.find { it.title == categoryName }?.demos ?: emptyList()

            val adapter = DemoGridAdapter(demos) { demo ->
                val intent = Intent(this@BrowseGridActivity, DemoDetailsActivity::class.java)
                intent.putExtra("demo", demo)
                startActivity(intent)
            }
            recyclerView.adapter = adapter
        }
    }

    class GridSpacingDecoration(
        private val spanCount: Int,
        private val spacing: Int
    ) : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            outRect.left = spacing
            outRect.right = spacing
            outRect.bottom = spacing
            outRect.top = spacing
        }
    }
}
