package com.demoscene.tv.ui
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.leanback.app.BrowseSupportFragment
import androidx.leanback.widget.*
import com.demoscene.tv.DemoDetailsActivity
import com.demoscene.tv.data.DemoDataProvider
import com.demoscene.tv.data.PouetCache
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class BrowseFragment : BrowseSupportFragment() {
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        
        // Check if filtering to specific category
        val categoryFilter = activity?.intent?.getStringExtra("CATEGORY_FILTER")
        
        if (categoryFilter != null) {
            // Show only one category - hide sidebar
            headersState = HEADERS_HIDDEN
        } else {
            // Show all categories with sidebar (old menu)
            headersState = HEADERS_ENABLED
        }
        
        isHeadersTransitionOnBackEnabled = true
        loadCategories(categoryFilter)
    }
    
    private fun loadCategories(filterCategory: String? = null) {
        CoroutineScope(Dispatchers.Main).launch {
            try {
                val hasCache = withContext(Dispatchers.IO) {
                    PouetCache.isCached(requireContext())
                }
                if (!hasCache) {
                    Log.d("DemosceneTV", "No cache yet, waiting for download...")
                    showLoadingScreen()
                    while (!PouetCache.isCached(requireContext())) {
                        delay(2000)
                    }
                    Log.d("DemosceneTV", "Cache ready! Loading categories...")
                }
                val categories = DemoDataProvider.getCategoryRows(requireContext())
                Log.d("DemosceneTV", "Got " + categories.size.toString() + " categories")
                
                val rowsAdapter = ArrayObjectAdapter(ListRowPresenter())
                val cardPresenter = CardPresenter()
                
                for (category in categories) {
                    // If filtering, only show the matching category
                    if (filterCategory != null && category.title != filterCategory) {
                        continue
                    }
                    
                    val listRowAdapter = ArrayObjectAdapter(cardPresenter)
                    for (demo in category.demos) {
                        listRowAdapter.add(demo)
                    }
                    
                    // Hide header text when filtering
                    val header = if (filterCategory != null) {
                        HeaderItem("")
                    } else {
                        HeaderItem(category.title)
                    }
                    rowsAdapter.add(ListRow(header, listRowAdapter))
                }
                adapter = rowsAdapter
                onItemViewClickedListener = OnItemViewClickedListener { _, item, _, _ ->
                    if (item is com.demoscene.tv.model.Demo) {
                        Log.d("DemosceneTV", "Opening details for: " + item.title)
                        val intent = Intent(requireContext(), DemoDetailsActivity::class.java)
                        intent.putExtra("demo", item)
                        startActivity(intent)
                    }
                }
            } catch (e: Exception) {
                Log.e("DemosceneTV", "Error loading categories: " + (e.message ?: "Unknown"), e)
            }
        }
    }
    
    private fun showLoadingScreen() {
        val rowsAdapter = ArrayObjectAdapter(ListRowPresenter())
        val header = HeaderItem("Downloading demo database...")
        val listRowAdapter = ArrayObjectAdapter(CardPresenter())
        rowsAdapter.add(ListRow(header, listRowAdapter))
        adapter = rowsAdapter
    }
}
