package com.demoscene.tv

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.demoscene.tv.model.Demo
import com.demoscene.tv.ui.MarbleButtonHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.URL

class DemoDetailsActivity : FragmentActivity() {

    private lateinit var btnPlay: Button

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

        val demo = intent.getParcelableExtra<Demo>("demo") ?: run {
            finish()
            return
        }

        val screenshotView = findViewById<ImageView>(R.id.demo_screenshot)
        Glide.with(this)
            .load(demo.thumbnailUrl)
            .into(screenshotView)

        findViewById<TextView>(R.id.demo_title).text = demo.title
        findViewById<TextView>(R.id.demo_metadata).text = 
            demo.year.toString() + " • " + demo.group + " • " + demo.platform

        findViewById<TextView>(R.id.demo_rating).text = String.format("%.1f", demo.rating)

        findViewById<TextView>(R.id.pouet_loves).text = "👍 ${demo.voteUp}"

        val youtubeLovesView = findViewById<TextView>(R.id.youtube_loves)
        fetchYoutubeLikes(demo.youtubeUrl, youtubeLovesView)

        btnPlay = findViewById(R.id.btn_play)
        val btnMoreByGroup = findViewById<Button>(R.id.btn_more_by_group)

        MarbleButtonHelper.applyRandomMarble(this, btnPlay)
        MarbleButtonHelper.applyRandomMarble(this, btnMoreByGroup)

        btnPlay.setOnClickListener {
            val intent = Intent(this, PlayerActivity::class.java)
            intent.putExtra("DEMO_YOUTUBE_URL", demo.youtubeUrl)
            startActivity(intent)
        }

        btnMoreByGroup.setOnClickListener {
            val intent = Intent(this, BrowseGridActivity::class.java)
            intent.putExtra("SEARCH_GROUP", demo.group)
            startActivity(intent)
        }
        
        btnPlay.requestFocus()
    }
    
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // UP from Play button shows menu
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && btnPlay.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 fetchYoutubeLikes(youtubeUrl: String, textView: TextView) {
        CoroutineScope(Dispatchers.Main).launch {
            try {
                val videoId = extractVideoId(youtubeUrl)
                if (videoId == null) {
                    textView.text = "👍 --"
                    return@launch
                }
                
                val likes = withContext(Dispatchers.IO) {
                    fetchLikesFromApi(videoId)
                }
                
                if (likes != null && likes >= 0) {
                    textView.text = "👍 ${formatNumber(likes)}"
                } else {
                    textView.text = "👍 --"
                }
            } catch (e: Exception) {
                Log.e("DemosceneTV", "Error fetching YouTube likes: ${e.message}")
                textView.text = "👍 --"
            }
        }
    }
    
    private fun extractVideoId(url: String): String? {
        val patterns = listOf(
            "youtube\\.com/watch\\?v=([a-zA-Z0-9_-]+)",
            "youtu\\.be/([a-zA-Z0-9_-]+)",
            "youtube\\.com/embed/([a-zA-Z0-9_-]+)",
            "youtube\\.com/v/([a-zA-Z0-9_-]+)"
        )
        for (pattern in patterns) {
            val regex = Regex(pattern)
            val match = regex.find(url)
            if (match != null) return match.groupValues[1]
        }
        return null
    }
    
    private fun fetchLikesFromApi(videoId: String): Long? {
        try {
            val rydUrl = "https://returnyoutubedislikeapi.com/votes?videoId=$videoId"
            val rydResponse = URL(rydUrl).readText()
            val rydJson = JSONObject(rydResponse)
            return rydJson.optLong("likes", -1).takeIf { it >= 0 }
        } catch (e: Exception) {
            Log.e("DemosceneTV", "API error: ${e.message}")
            return null
        }
    }
    
    private fun formatNumber(num: Long): String {
        return when {
            num >= 1_000_000 -> String.format("%.1fM", num / 1_000_000.0)
            num >= 1_000 -> String.format("%.1fK", num / 1_000.0)
            else -> num.toString()
        }
    }
}
