using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// Debug helper for testing battle scene transitions and victory scenarios
/// </summary>
public class BattleSceneDebugHelper : MonoBehaviour
{
    [Header("Debug Controls")]
    [Tooltip("Enable debug mode to show additional logging and controls")]
    public bool enableDebugMode = true;

    [Header("Scene Testing")]
    [Tooltip("Name of the map scene to return to")]
    public string mapSceneName = "MapScene2";

    private void Update()
    {
        if (!enableDebugMode) return;

        // Debug hotkeys
        if (Input.GetKeyDown(KeyCode.F1))
        {
            TestSceneTransition();
        }

        if (Input.GetKeyDown(KeyCode.F2))
        {
            ForcePlayerVictory();
        }

        if (Input.GetKeyDown(KeyCode.F3))
        {
            TestReturnToMap();
        }
    }

    [ContextMenu("Test Scene Transition")]
    public void TestSceneTransition()
    {
        Debug.Log("🧪 [DEBUG] Testing scene transition to " + mapSceneName);

        try
        {
            SceneManager.LoadScene(mapSceneName);
            Debug.Log("✅ Scene transition initiated successfully");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"❌ Scene transition failed: {e.Message}");
        }
    }

    [ContextMenu("Force Player Victory")]
    public void ForcePlayerVictory()
    {
        Debug.Log("🧪 [DEBUG] Forcing player victory...");

        if (GameManager.Instance != null)
        {
            // Use the GameManager's test victory method if available
            var method = typeof(GameManager).GetMethod("TestBattleVictory",
                System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            if (method != null)
            {
                method.Invoke(GameManager.Instance, null);
                Debug.Log("✅ Used GameManager.TestBattleVictory()");
            }
            else
            {
                Debug.LogWarning("⚠️ GameManager.TestBattleVictory() method not found");
                // Manually kill all enemies
                ForceKillAllEnemies();
            }
        }
        else
        {
            Debug.LogError("❌ GameManager.Instance is null");
        }
    }

    [ContextMenu("Test Return to Map")]
    public void TestReturnToMap()
    {
        Debug.Log("🧪 [DEBUG] Testing return to map via OnLootingComplete...");

        if (GameManager.Instance != null)
        {
            // Call the OnLootingComplete method directly
            var method = typeof(GameManager).GetMethod("OnLootingComplete",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            if (method != null)
            {
                method.Invoke(GameManager.Instance, null);
                Debug.Log("✅ Called OnLootingComplete() via reflection");
            }
            else
            {
                Debug.LogError("❌ OnLootingComplete method not found");
            }
        }
        else
        {
            Debug.LogError("❌ GameManager.Instance is null");
        }
    }

    private void ForceKillAllEnemies()
    {
        Debug.Log("🧪 [DEBUG] Manually killing all enemies...");

        if (GameManager.Instance != null && GameManager.Instance.enemyCharacters != null)
        {
            foreach (var enemy in GameManager.Instance.enemyCharacters)
            {
                if (enemy != null)
                {
                    var character = enemy.GetComponent<Character>();
                    if (character != null && !character.IsDead)
                    {
                        character.TakeDamage(1000); // Force death
                        Debug.Log($"🔪 Killed enemy: {enemy.name}");
                    }
                }
            }
        }
    }

    [ContextMenu("Debug Battle State")]
    public void DebugBattleState()
    {
        Debug.Log("🔍 [DEBUG] Current battle state:");

        if (GameManager.Instance != null)
        {
            Debug.Log($"  Players: {GameManager.Instance.playerCharacters?.Count ?? 0}");
            Debug.Log($"  Enemies: {GameManager.Instance.enemyCharacters?.Count ?? 0}");

            var alivePlayers = GameManager.Instance.GetAlivePlayers();
            var aliveEnemies = GameManager.Instance.enemyCharacters?.Where(e => e != null && !e.GetComponent<Character>()?.IsDead == true).Count() ?? 0;

            Debug.Log($"  Alive Players: {alivePlayers?.Count ?? 0}");
            Debug.Log($"  Alive Enemies: {aliveEnemies}");

            bool battleShouldEnd = (alivePlayers?.Count ?? 0) == 0 || aliveEnemies == 0;
            Debug.Log($"  Battle should end: {battleShouldEnd}");
        }
        else
        {
            Debug.LogError("  GameManager.Instance is null!");
        }
    }

    private void OnGUI()
    {
        if (!enableDebugMode) return;

        // Simple debug GUI
        GUILayout.BeginArea(new Rect(10, 10, 300, 200));
        GUILayout.Label("Battle Debug Controls", GUI.skin.box);

        if (GUILayout.Button("F1: Test Scene Transition"))
            TestSceneTransition();

        if (GUILayout.Button("F2: Force Player Victory"))
            ForcePlayerVictory();

        if (GUILayout.Button("F3: Test Return to Map"))
            TestReturnToMap();

        if (GUILayout.Button("Debug Battle State"))
            DebugBattleState();

        GUILayout.Label("Hotkeys: F1, F2, F3");
        GUILayout.EndArea();
    }
}
