package com.pixelmintdrop

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.pixelmintdrop.databinding.HighScoresBinding
import com.pixelmintdrop.model.HighScoreAdapter
import com.pixelmintdrop.model.HighScoreManager
import com.pixelmintdrop.model.PlayerProgressionManager
import com.pixelmintdrop.model.GooglePlayGamesManager
import android.graphics.Color
import android.util.Log
import android.view.KeyEvent
import android.view.InputDevice
import android.graphics.Rect
import android.view.View
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import android.content.Intent

class HighScoresActivity : AppCompatActivity() {
    private lateinit var binding: HighScoresBinding
    private lateinit var highScoreManager: HighScoreManager
    private lateinit var highScoreAdapter: HighScoreAdapter
    private lateinit var progressionManager: PlayerProgressionManager
    private var currentTheme = PlayerProgressionManager.THEME_CLASSIC
    
    companion object {
        private const val RC_LEADERBOARD_UI_HS = 9005 // Unique request code for HighScoresActivity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        try {
            binding = HighScoresBinding.inflate(layoutInflater)
            setContentView(binding.root)
            
            // Apply insets to the root view
            val initialPadding = Rect(binding.root.paddingLeft, binding.root.paddingTop,
                                    binding.root.paddingRight, binding.root.paddingBottom)
            ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets ->
                val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
                view.updatePadding(
                    left = initialPadding.left + insets.left,
                    top = initialPadding.top + insets.top,
                    right = initialPadding.right + insets.right,
                    bottom = initialPadding.bottom + insets.bottom
                )
                WindowInsetsCompat.CONSUMED
            }
            
            highScoreManager = HighScoreManager(this)
            progressionManager = PlayerProgressionManager(this)
            
            // Load and apply theme
            currentTheme = loadThemePreference()
            
            // Initialize adapter before applying theme
            highScoreAdapter = HighScoreAdapter()
            
            // Set up RecyclerView
            binding.highScoresList.layoutManager = LinearLayoutManager(this)
            binding.highScoresList.adapter = highScoreAdapter
            
            // Now apply theme to UI
            applyTheme(currentTheme)
            
            // Load high scores
            updateHighScores()
            
            // Set up back button
            binding.backButton.setOnClickListener {
                finish()
            }
            
            // Set up leaderboard button
            binding.leaderboardButton?.setOnClickListener {
                showGlobalLeaderboard()
            }
        } catch (e: Exception) {
            Log.e("HighScoresActivity", "Error in onCreate", e)
            // Show an error message if necessary, or finish gracefully
            finish()
        }
    }

    private fun loadThemePreference(): String {
        return progressionManager.getSelectedTheme()
    }

    private fun applyTheme(themeId: String) {
        try {
            // Set background color
            val backgroundColor = when (themeId) {
                PlayerProgressionManager.THEME_CLASSIC -> Color.BLACK
                PlayerProgressionManager.THEME_NEON -> Color.parseColor("#0D0221")
                PlayerProgressionManager.THEME_MONOCHROME -> Color.parseColor("#1A1A1A")
                PlayerProgressionManager.THEME_RETRO -> Color.parseColor("#3F2832")
                PlayerProgressionManager.THEME_MINIMALIST -> Color.WHITE
                PlayerProgressionManager.THEME_GALAXY -> Color.parseColor("#0B0C10")
                else -> Color.BLACK
            }
            binding.root.setBackgroundColor(backgroundColor)
    
            // Set text color
            val textColor = when (themeId) {
                PlayerProgressionManager.THEME_CLASSIC -> Color.WHITE
                PlayerProgressionManager.THEME_NEON -> Color.parseColor("#FF00FF")
                PlayerProgressionManager.THEME_MONOCHROME -> Color.LTGRAY
                PlayerProgressionManager.THEME_RETRO -> Color.parseColor("#FF5A5F")
                PlayerProgressionManager.THEME_MINIMALIST -> Color.BLACK
                PlayerProgressionManager.THEME_GALAXY -> Color.parseColor("#66FCF1")
                else -> Color.WHITE
            }
    
            // Apply theme to buttons
            binding.backButton.setTextColor(textColor)
            binding.leaderboardButton?.setTextColor(textColor)
    
            // Update adapter theme
            highScoreAdapter.applyTheme(themeId)
        } catch (e: Exception) {
            Log.e("HighScoresActivity", "Error applying theme: $themeId", e)
        }
    }

    private fun updateHighScores() {
        try {
            val scores = highScoreManager.getHighScores()
            highScoreAdapter.updateHighScores(scores)
        } catch (e: Exception) {
            Log.e("HighScoresActivity", "Error updating high scores", e)
        }
    }
    
    private fun showGlobalLeaderboard() {
        try {
            if (!highScoreManager.isGooglePlaySignedIn()) {
                Toast.makeText(this, "Signing in to Google Play Games...", Toast.LENGTH_SHORT).show()
            }
            
            // Call the updated showLeaderboard with a listener
            highScoreManager.getGooglePlayGamesManager().showLeaderboard(this, 
                object : GooglePlayGamesManager.LeaderboardIntentListener {
                    override fun onLeaderboardIntentSuccess(intent: Intent) {
                        try {
                            startActivityForResult(intent, RC_LEADERBOARD_UI_HS)
                        } catch (e: Exception) {
                            Log.e("HighScoresActivity", "Failed to start leaderboard activity for result", e)
                            Toast.makeText(this@HighScoresActivity, "Could not display leaderboard.", Toast.LENGTH_SHORT).show()
                        }
                    }

                    override fun onLeaderboardIntentFailure(exception: Exception) {
                        Log.e("HighScoresActivity", "Failed to get leaderboard intent.", exception)
                        Toast.makeText(this@HighScoresActivity, "Could not display leaderboard.", Toast.LENGTH_SHORT).show()
                    }
                })
        } catch (e: Exception) {
            Log.e("HighScoresActivity", "Error showing leaderboard", e)
            Toast.makeText(this, "Could not open leaderboard", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHighScores()
        } catch (e: Exception) {
            Log.e("HighScoresActivity", "Error in onResume", e)
        }
    }

    // Handle gamepad buttons
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // Check if it's a gamepad input
        if (event != null && isGamepadDevice(event.device)) {
            when (keyCode) {
                KeyEvent.KEYCODE_BUTTON_B,
                KeyEvent.KEYCODE_BACK -> {
                    // B button or Back button returns to previous screen
                    finish()
                    return true
                }
                KeyEvent.KEYCODE_BUTTON_Y -> {
                    // Y button shows global leaderboard
                    showGlobalLeaderboard()
                    return true
                }
            }
        }
        
        return super.onKeyDown(keyCode, event)
    }
    
    // Helper function to check if the device is a gamepad
    private fun isGamepadDevice(device: InputDevice?): Boolean {
        if (device == null) return false
        val sources = device.sources
        return (sources and InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD ||
               (sources and InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK
    }
} 