using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Test mode for battle scene that creates test characters and enemies automatically
/// Attach this to a GameObject in the battle scene to enable test mode
/// Enhanced with post-battle looting and defeat testing capabilities
/// </summary>
public class BattleTestMode : MonoBehaviour
{
    [Header("Test Mode Settings")]
    [Tooltip("Enable test mode to automatically create test characters")]
    public bool enableTestMode = true;

    [Tooltip("Number of player characters to create")]
    [Range(1, 4)]
    public int testPlayerCount = 2;

    [Tooltip("Number of enemy characters to create")]
    [Range(1, 6)]
    public int testEnemyCount = 2;

    [Header("Test Character Configuration")]
    [Tooltip("Available weapon types for testing")]
    public string[] availableWeapons = { "Sword", "Bow", "Fists" };

    [Tooltip("Player character names - Character 0: Fast (DEX:20→Speed:40), Character 1: Slow (DEX:4→Speed:25)")]
    public string[] playerNames = { "FastRogue", "SlowTank", "TestMage", "TestRogue" };

    [Tooltip("Enemy character names")]
    public string[] enemyNames = { "TestSkeleton", "TestBandit", "TestOrc", "TestGoblin", "TestTroll", "TestSpider" };

    [Header("Debug Settings")]
    public bool showDebugLogs = true;

    [Tooltip("Force clear existing battle data and use test mode anyway")]
    public bool forceClearExistingData = false;

    void Awake()
    {
        if (!enableTestMode)
        {
            if (showDebugLogs)
                Debug.Log("🧪 BattleTestMode: Test mode is disabled");
            return;
        }

        if (showDebugLogs)
        {
            Debug.Log($"🧪 BattleTestMode: Current battle data - Players: {BattleSetupData.playerSelections.Count}, Enemies: {BattleSetupData.enemySelections.Count}");
        }

        // Force clear existing data if requested
        if (forceClearExistingData)
        {
            if (showDebugLogs)
                Debug.Log("🧪 BattleTestMode: Force clearing existing battle data");
            BattleSetupData.playerSelections.Clear();
            BattleSetupData.enemySelections.Clear();
        }

        // Only activate test mode if there are no existing selections
        if (BattleSetupData.playerSelections.Count == 0 && BattleSetupData.enemySelections.Count == 0)
        {
            CreateTestBattleData();
        }
        else
        {
            if (showDebugLogs)
                Debug.Log($"🧪 BattleTestMode: Battle data already exists, skipping test mode. Players: {BattleSetupData.playerSelections.Count}, Enemies: {BattleSetupData.enemySelections.Count}");
        }
    }

    void CreateTestBattleData()
    {
        if (showDebugLogs)
            Debug.Log("🧪 BattleTestMode: Creating test battle data...");

        // Clear any existing data
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();

        // Create test player characters
        CreateTestPlayers();

        // Create test enemy characters
        CreateTestEnemies();

        // Create basic inventory data for the test characters
        CreateBasicInventoryData();

        // Add carry capacity components to test characters
        AddCarryCapacityToTestCharacters();

        if (showDebugLogs)
        {
            Debug.Log($"🧪 BattleTestMode: Created {BattleSetupData.playerSelections.Count} test players and {BattleSetupData.enemySelections.Count} test enemies");
            LogTestData();
        }
    }

    /// <summary>
    /// Create test player characters with varied weapons
    /// </summary>
    void CreateTestPlayers()
    {
        for (int i = 0; i < testPlayerCount; i++)
        {
            string playerName = i < playerNames.Length ? playerNames[i] : $"TestPlayer{i + 1}";
            string weaponType = availableWeapons[i % availableWeapons.Length];

            var playerSelection = new CharacterSelection
            {
                characterName = playerName,
                weaponType = weaponType
            };

            BattleSetupData.playerSelections.Add(playerSelection);

            if (showDebugLogs)
                Debug.Log($"🧪 Created test player: {playerName} with {weaponType}");
        }
    }

    /// <summary>
    /// Create test enemy characters with varied weapons
    /// </summary>
    void CreateTestEnemies()
    {
        for (int i = 0; i < testEnemyCount; i++)
        {
            string enemyName = i < enemyNames.Length ? enemyNames[i] : $"TestEnemy{i + 1}";
            string weaponType = availableWeapons[Random.Range(0, availableWeapons.Length)];

            var enemySelection = new CharacterSelection
            {
                characterName = enemyName,
                weaponType = weaponType
            };

            BattleSetupData.enemySelections.Add(enemySelection);

            if (showDebugLogs)
                Debug.Log($"🧪 Created test enemy: {enemyName} with {weaponType}");
        }
    }

    /// <summary>
    /// Log all test data for debugging
    /// </summary>
    void LogTestData()
    {
        Debug.Log("🧪 === Test Battle Data ===");
        Debug.Log($"🧪 Players ({BattleSetupData.playerSelections.Count}):");
        foreach (var player in BattleSetupData.playerSelections)
        {
            Debug.Log($"🧪   - {player.characterName} ({player.weaponType})");
        }

        Debug.Log($"🧪 Enemies ({BattleSetupData.enemySelections.Count}):");
        foreach (var enemy in BattleSetupData.enemySelections)
        {
            Debug.Log($"🧪   - {enemy.characterName} ({enemy.weaponType})");
        }
        Debug.Log("🧪 ========================");
    }

    /// <summary>
    /// Create basic inventory data for test characters using CombatDataTransfer
    /// </summary>
    void CreateBasicInventoryData()
    {
        // Create minimal combat session data to provide inventory
        var sessionData = new CombatDataTransfer.CombatSessionData
        {
            battleTerrain = TerrainType.Plains,
            battleFeature = FeatureType.None,
            weather = Weather.Clear,
            timeOfDay = 12f,
            playerTeam = new List<CombatDataTransfer.TeamCharacterCombatData>(),
            enemies = new List<CombatDataTransfer.EnemyCombatData>()
        };

        // Create specialized test characters with different movement speeds
        CreateSpecializedTestCharacters(sessionData);

        // Create basic enemy data (no inventory needed for enemies)
        for (int i = 0; i < BattleSetupData.enemySelections.Count; i++)
        {
            var enemy = BattleSetupData.enemySelections[i];
            var enemyData = new CombatDataTransfer.EnemyCombatData
            {
                enemyName = enemy.characterName,
                maxHealth = 15 + Random.Range(-3, 8),
                currentHealth = 15 + Random.Range(-3, 8),
                armorClass = 11,
                preferredWeapon = enemy.weaponType,
                threatLevel = Random.Range(1, 4)
            };
            sessionData.enemies.Add(enemyData);
        }

        // Set the combat session
        CombatDataTransfer.SetCombatSession(sessionData);

        if (showDebugLogs)
            Debug.Log($"🧪 Created basic inventory data for {sessionData.playerTeam.Count} players");
    }

    /// <summary>
    /// Create specialized test characters with different movement speeds and attributes
    /// </summary>
    void CreateSpecializedTestCharacters(CombatDataTransfer.CombatSessionData sessionData)
    {
        for (int i = 0; i < BattleSetupData.playerSelections.Count; i++)
        {
            var player = BattleSetupData.playerSelections[i];
            CombatDataTransfer.TeamCharacterCombatData playerData;

            // Create different character archetypes
            switch (i)
            {
                case 0: // VERY Fast character - Extreme High Dexterity
                    playerData = new CombatDataTransfer.TeamCharacterCombatData
                    {
                        characterName = player.characterName,
                        maxHealth = 18,
                        currentHealth = 18,
                        armorClass = 13,
                        equippedWeapon = player.weaponType,
                        strength = 12,
                        dexterity = 30, // Extreme High DEX = Very Fast movement (MovementSpeed = 30 + 20 = 50)
                        constitution = 14,
                        wisdom = 12,
                        perception = 16,
                        miscItems = CreateBasicTestInventory(i)
                    };
                    if (showDebugLogs)
                        Debug.Log($"🧪 Created VERY FAST character: {player.characterName} - DEX:30 (Expected MovementSpeed: 50)");
                    break;

                case 1: // VERY Slow character - Extremely Low Dexterity
                    playerData = new CombatDataTransfer.TeamCharacterCombatData
                    {
                        characterName = player.characterName,
                        maxHealth = 25,
                        currentHealth = 25,
                        armorClass = 11,
                        equippedWeapon = player.weaponType,
                        strength = 16,
                        dexterity = 1, // Very Low DEX = Slow movement (MovementSpeed = 30 + (-5) = 25)
                        constitution = 16,
                        wisdom = 14,
                        perception = 10,
                        miscItems = CreateBasicTestInventory(i)
                    };
                    if (showDebugLogs)
                        Debug.Log($"🧪 Created VERY SLOW character: {player.characterName} - DEX:1 (Expected MovementSpeed: 25)");
                    break;
                default: // Balanced character for any additional characters
                    playerData = new CombatDataTransfer.TeamCharacterCombatData
                    {
                        characterName = player.characterName,
                        maxHealth = 22,
                        currentHealth = 22,
                        armorClass = 12,
                        equippedWeapon = player.weaponType,
                        strength = 14,
                        dexterity = 14, // Average DEX = Average movement (MovementSpeed = 30 + 4*5 = 50)
                        constitution = 14,
                        wisdom = 12,
                        perception = 12,
                        miscItems = CreateBasicTestInventory(i)
                    };
                    if (showDebugLogs)
                        Debug.Log($"🧪 Created BALANCED character: {player.characterName} - DEX:14 (Expected MovementSpeed: ~50)");
                    break;
            }

            sessionData.playerTeam.Add(playerData);
        }
    }

    /// <summary>
    /// Create a basic test inventory with health potions and other items
    /// </summary>
    List<string> CreateBasicTestInventory(int characterIndex)
    {
        var inventory = new List<string>();

        // Everyone gets health potions
        inventory.Add("Health Potion");
        inventory.Add("Health Potion"); // Give 2 health potions

        // Basic survival items
        inventory.Add("Bread");
        inventory.Add("Bandage");

        // Add some variety based on character index
        switch (characterIndex % 3)
        {
            case 0:
                inventory.Add("Health Potion"); // Extra healing for first character
                inventory.Add("Iron Ration");
                break;
            case 1:
                inventory.Add("Antidote");
                inventory.Add("Rope");
                break;
            case 2:
                inventory.Add("Torch");
                inventory.Add("Waterskin");
                break;
        }

        return inventory;
    }

    /// <summary>
    /// Add carry capacity components to test characters for weight management
    /// </summary>
    void AddCarryCapacityToTestCharacters()
    {
        // This will add carry capacity to actual character GameObjects when they're spawned
        // For now, just log that this system is available
        if (showDebugLogs)
            Debug.Log("🧪 Carry capacity system ready for test characters");

        // TODO: This method will be called after character spawning when the actual GameObjects exist
        // It would add CharacterCarryCapacity components to each spawned character
    }

    /// <summary>
    /// Context menu method to manually create test data
    /// </summary>
    [ContextMenu("Create Test Battle Data")]
    public void ManualCreateTestData()
    {
        CreateTestBattleData();
    }

    /// <summary>
    /// Context menu method to clear test data
    /// </summary>
    [ContextMenu("Clear Test Data")]
    public void ClearTestData()
    {
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();
        CombatDataTransfer.ClearSession();

        if (showDebugLogs)
            Debug.Log("🧪 BattleTestMode: Test data and inventory cleared");
    }

    /// <summary>
    /// Context menu method to create random test data
    /// </summary>
    [ContextMenu("Create Random Test Data")]
    public void CreateRandomTestData()
    {
        // Randomize counts
        testPlayerCount = Random.Range(1, 5);
        testEnemyCount = Random.Range(1, 7);

        CreateTestBattleData();
    }

    /// <summary>
    /// Create a quick 1v1 battle for testing specific mechanics
    /// </summary>
    [ContextMenu("Create 1v1 Test Battle")]
    public void Create1v1TestBattle()
    {
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();

        // Single player with sword
        BattleSetupData.playerSelections.Add(new CharacterSelection
        {
            characterName = "TestHero",
            weaponType = "Sword"
        });

        // Single enemy with bow
        BattleSetupData.enemySelections.Add(new CharacterSelection
        {
            characterName = "TestSkeleton",
            weaponType = "Bow"
        });

        // Create inventory data for the 1v1 battle
        CreateBasicInventoryData();

        if (showDebugLogs)
            Debug.Log("🧪 Created 1v1 test battle: TestHero (Sword) vs TestSkeleton (Bow)");
    }

    /// <summary>
    /// Create a larger battle for stress testing
    /// </summary>
    [ContextMenu("Create Large Test Battle")]
    public void CreateLargeTestBattle()
    {
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();

        // Create 4 players with different weapons
        for (int i = 0; i < 4; i++)
        {
            BattleSetupData.playerSelections.Add(new CharacterSelection
            {
                characterName = playerNames[i],
                weaponType = availableWeapons[i % availableWeapons.Length]
            });
        }

        // Create 6 enemies with random weapons
        for (int i = 0; i < 6; i++)
        {
            BattleSetupData.enemySelections.Add(new CharacterSelection
            {
                characterName = enemyNames[i],
                weaponType = availableWeapons[Random.Range(0, availableWeapons.Length)]
            });
        }

        // Create inventory data for the large battle
        CreateBasicInventoryData();

        if (showDebugLogs)
            Debug.Log("🧪 Created large test battle: 4 players vs 6 enemies");
    }

    /// <summary>
    /// Create a test battle designed to test victory looting (weak enemies)
    /// </summary>
    [ContextMenu("Create Victory Test Battle")]
    public void CreateVictoryTestBattle()
    {
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();

        // Create 2 strong players
        for (int i = 0; i < 2; i++)
        {
            BattleSetupData.playerSelections.Add(new CharacterSelection
            {
                characterName = playerNames[i],
                weaponType = availableWeapons[i % availableWeapons.Length]
            });
        }

        // Create 3 weak enemies
        for (int i = 0; i < 3; i++)
        {
            BattleSetupData.enemySelections.Add(new CharacterSelection
            {
                characterName = enemyNames[i],
                weaponType = "Fists" // Weak weapon
            });
        }

        // Create enhanced session data with stronger players and weaker enemies
        var sessionData = new CombatDataTransfer.CombatSessionData
        {
            battleTerrain = TerrainType.Plains,
            battleFeature = FeatureType.None,
            weather = Weather.Clear,
            timeOfDay = 12f,
            playerTeam = new List<CombatDataTransfer.TeamCharacterCombatData>(),
            enemies = new List<CombatDataTransfer.EnemyCombatData>()
        };

        // Create strong player data
        for (int i = 0; i < BattleSetupData.playerSelections.Count; i++)
        {
            var player = BattleSetupData.playerSelections[i];
            var playerData = new CombatDataTransfer.TeamCharacterCombatData
            {
                characterName = player.characterName,
                maxHealth = 35, // Higher health
                currentHealth = 35,
                armorClass = 15, // Better armor
                equippedWeapon = player.weaponType,
                strength = 16, // High strength for carry capacity
                dexterity = 14,
                constitution = 16,
                wisdom = 12,
                perception = 14,
                miscItems = CreateBasicTestInventory(i)
            };
            sessionData.playerTeam.Add(playerData);
        }

        // Create weak enemy data
        for (int i = 0; i < BattleSetupData.enemySelections.Count; i++)
        {
            var enemy = BattleSetupData.enemySelections[i];
            var enemyData = new CombatDataTransfer.EnemyCombatData
            {
                enemyName = enemy.characterName,
                maxHealth = 5, // Very low health
                currentHealth = 5,
                armorClass = 8, // Poor armor
                preferredWeapon = enemy.weaponType,
                threatLevel = 1 // Low threat
            };
            sessionData.enemies.Add(enemyData);
        }

        CombatDataTransfer.SetCombatSession(sessionData);

        if (showDebugLogs)
            Debug.Log("🧪 Created victory test battle: 2 strong players vs 3 weak enemies (for testing post-battle looting)");
    }

    /// <summary>
    /// Create a test battle designed to test defeat (weak players)
    /// </summary>
    [ContextMenu("Create Defeat Test Battle")]
    public void CreateDefeatTestBattle()
    {
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();

        // Create 1 weak player
        BattleSetupData.playerSelections.Add(new CharacterSelection
        {
            characterName = "WeakHero",
            weaponType = "Fists"
        });

        // Create 2 strong enemies
        for (int i = 0; i < 2; i++)
        {
            BattleSetupData.enemySelections.Add(new CharacterSelection
            {
                characterName = enemyNames[i],
                weaponType = "Sword"
            });
        }

        // Create session data with weak player and strong enemies
        var sessionData = new CombatDataTransfer.CombatSessionData
        {
            battleTerrain = TerrainType.Forest,
            battleFeature = FeatureType.None,
            weather = Weather.Storm,
            timeOfDay = 20f, // Night
            playerTeam = new List<CombatDataTransfer.TeamCharacterCombatData>(),
            enemies = new List<CombatDataTransfer.EnemyCombatData>()
        };

        // Create weak player data
        var weakPlayer = new CombatDataTransfer.TeamCharacterCombatData
        {
            characterName = "WeakHero",
            maxHealth = 8, // Very low health
            currentHealth = 8,
            armorClass = 10, // Poor armor
            equippedWeapon = "Fists",
            strength = 8,
            dexterity = 8,
            constitution = 8,
            wisdom = 8,
            perception = 8,
            miscItems = new List<string> { "Health Potion" } // Minimal inventory
        };
        sessionData.playerTeam.Add(weakPlayer);

        // Create strong enemy data
        for (int i = 0; i < BattleSetupData.enemySelections.Count; i++)
        {
            var enemy = BattleSetupData.enemySelections[i];
            var enemyData = new CombatDataTransfer.EnemyCombatData
            {
                enemyName = enemy.characterName,
                maxHealth = 25, // High health
                currentHealth = 25,
                armorClass = 14, // Good armor
                preferredWeapon = "Sword",
                threatLevel = 5 // High threat
            };
            sessionData.enemies.Add(enemyData);
        }

        CombatDataTransfer.SetCombatSession(sessionData);

        if (showDebugLogs)
            Debug.Log("🧪 Created defeat test battle: 1 weak player vs 2 strong enemies (for testing game over screen)");
    }
}
