package com.demoscene.tv

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.EditText
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

class SearchActivity : FragmentActivity() {

    private lateinit var searchInput: EditText
    private lateinit var resultsTitle: TextView
    private lateinit var resultsGrid: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        
        searchInput = findViewById(R.id.search_input)
        resultsTitle = findViewById(R.id.results_title)
        resultsGrid = findViewById(R.id.search_results_grid)
        
        resultsGrid.layoutManager = GridLayoutManager(this, 5)
        val spacing = (8 * resources.displayMetrics.density).toInt()
        resultsGrid.addItemDecoration(BrowseGridActivity.GridSpacingDecoration(5, spacing))
        
        searchInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
                performSearch(searchInput.text.toString())
                true
            } else {
                false
            }
        }
        
        searchInput.requestFocus()
    }
    
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // UP from search input shows menu
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && searchInput.hasFocus()) {
            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 performSearch(query: String) {
        if (query.isBlank()) {
            resultsTitle.text = "Enter a search term"
            return
        }
        
        resultsTitle.text = "Searching..."
        
        CoroutineScope(Dispatchers.Main).launch {
            val demos = withContext(Dispatchers.IO) {
                DemoDataProvider.search(this@SearchActivity, query)
            }
            
            if (demos.isEmpty()) {
                resultsTitle.text = "No results for: $query"
            } else {
                resultsTitle.text = "${demos.size} results for: $query"
            }
            
            val adapter = DemoGridAdapter(demos) { demo ->
                val intent = Intent(this@SearchActivity, DemoDetailsActivity::class.java)
                intent.putExtra("demo", demo)
                startActivity(intent)
            }
            resultsGrid.adapter = adapter
        }
    }
}
