package com.pixelmintdrop

import android.app.Activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.pixelmintdrop.databinding.HighScoreEntryBinding
import com.pixelmintdrop.model.HighScore
import com.pixelmintdrop.model.HighScoreManager
import com.pixelmintdrop.model.PlayerProgressionManager
import android.graphics.Color
import android.view.KeyEvent
import android.view.InputDevice
import androidx.activity.OnBackPressedCallback

class HighScoreEntryActivity : AppCompatActivity() {
    private lateinit var binding: HighScoreEntryBinding
    private lateinit var highScoreManager: HighScoreManager
    private lateinit var progressionManager: PlayerProgressionManager
    private var currentTheme = PlayerProgressionManager.THEME_CLASSIC
    private var score: Int = 0
    
    // Track if we already saved to prevent double-saving
    private var hasSaved = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = HighScoreEntryBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Set up back button handling
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // If they haven't saved yet, consider it a cancel
                if (!hasSaved) {
                    setResult(Activity.RESULT_CANCELED)
                }
                finish()
            }
        })

        highScoreManager = HighScoreManager(this)
        progressionManager = PlayerProgressionManager(this)
        
        // Load and apply theme
        currentTheme = loadThemePreference()
        applyTheme(currentTheme)

        score = intent.getIntExtra("score", 0)
        binding.scoreText.text = "Score: $score"

        binding.saveButton.setOnClickListener {
            saveScore()
        }
    }
    
    private fun saveScore() {
        // Only allow saving once
        if (!hasSaved) {
            val name = binding.nameInput.text.toString().trim()
            if (name.isNotEmpty()) {
                hasSaved = true
                val highScore = HighScore(name, score, 1)
                highScoreManager.addHighScore(highScore)
                
                // Set result and finish
                setResult(Activity.RESULT_OK)
                finish()
            }
        }
    }
    
    // Override onKeyDown to 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_A,
                KeyEvent.KEYCODE_DPAD_CENTER -> {
                    // A button saves the score
                    saveScore()
                    return true
                }
                KeyEvent.KEYCODE_BUTTON_B -> {
                    // B button cancels
                    setResult(Activity.RESULT_CANCELED)
                    finish()
                    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
    }

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

    private fun applyTheme(themeId: String) {
        // 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 text color to score and input
        binding.scoreText.setTextColor(textColor)
        binding.nameInput.setTextColor(textColor)
        binding.nameInput.setHintTextColor(Color.argb(128, Color.red(textColor), Color.green(textColor), Color.blue(textColor)))

        // Apply theme to submit button
        binding.saveButton.setTextColor(textColor)
    }
} 