using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Enhanced test mode that creates both BattleSetupData and CombatDataTransfer test data
/// This provides more realistic character stats, equipment, and battle context
/// </summary>
public class EnhancedBattleTestMode : MonoBehaviour
{
    [Header("Enhanced Test Mode Settings")]
    [Tooltip("Enable enhanced test mode with full combat data")]
    public bool enableEnhancedTestMode = 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("Battle Context Settings")]
    [Tooltip("Test terrain type")]
    public TerrainType testTerrain = TerrainType.Plains;

    [Tooltip("Test weather")]
    public Weather testWeather = Weather.Clear;

    [Tooltip("Test time of day (0-24)")]
    [Range(0f, 24f)]
    public float testTimeOfDay = 12f;

    [Header("Character Stats Settings")]
    [Tooltip("Base health for test players")]
    [Range(10, 100)]
    public int basePlayerHealth = 25;

    [Tooltip("Base health for test enemies")]
    [Range(5, 50)]
    public int baseEnemyHealth = 15;

    [Tooltip("Base armor class for test characters")]
    [Range(8, 18)]
    public int baseArmorClass = 12;

    [Header("Available Equipment")]
    public WeaponItem[] testWeapons;

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

    // Test character names
    private readonly string[] playerNames = { "FastRogue", "SlowTank", "TestMage", "TestRogue" };
    private readonly string[] enemyNames = { "TestSkeleton", "TestBandit", "TestOrc", "TestGoblin", "TestTroll", "TestSpider" };

    void Awake()
    {
        if (!enableEnhancedTestMode)
        {
            if (showDebugLogs)
                Debug.Log("🧪 EnhancedBattleTestMode: Enhanced test mode is disabled");
            return;
        }

        // Only activate if no existing data
        if (!CombatDataTransfer.HasValidSession() &&
            BattleSetupData.playerSelections.Count == 0 &&
            BattleSetupData.enemySelections.Count == 0)
        {
            CreateEnhancedTestData();
        }
        else
        {
            if (showDebugLogs)
                Debug.Log("🧪 EnhancedBattleTestMode: Combat session or battle data already exists, skipping test mode");
        }
    }

    /// <summary>
    /// Create comprehensive test data including combat session and battle setup data
    /// </summary>
    void CreateEnhancedTestData()
    {
        if (showDebugLogs)
            Debug.Log("🧪 EnhancedBattleTestMode: Creating enhanced test data...");

        // Create test combat session
        CreateTestCombatSession();

        // Create legacy battle setup data for compatibility
        CreateTestBattleSetupData();

        if (showDebugLogs)
        {
            Debug.Log("🧪 EnhancedBattleTestMode: Enhanced test data created successfully");
            LogEnhancedTestData();
        }
    }

    /// <summary>
    /// Create a test combat session with realistic character data
    /// </summary>
    void CreateTestCombatSession()
    {
        var sessionData = new CombatDataTransfer.CombatSessionData
        {
            battleTerrain = testTerrain,
            battleFeature = FeatureType.None,
            weather = testWeather,
            timeOfDay = testTimeOfDay,
            playerTeam = new List<CombatDataTransfer.TeamCharacterCombatData>(),
            enemies = new List<CombatDataTransfer.EnemyCombatData>()
        };

        // Create test players
        for (int i = 0; i < testPlayerCount; i++)
        {
            var playerData = CreateTestPlayerData(i);
            sessionData.playerTeam.Add(playerData);
        }

        // Create test enemies
        for (int i = 0; i < testEnemyCount; i++)
        {
            var enemyData = CreateTestEnemyData(i);
            sessionData.enemies.Add(enemyData);
        }

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

        if (showDebugLogs)
            Debug.Log($"🧪 Created combat session with {sessionData.playerTeam.Count} players and {sessionData.enemies.Count} enemies");
    }

    /// <summary>
    /// Create test player character data
    /// </summary>
    CombatDataTransfer.TeamCharacterCombatData CreateTestPlayerData(int index)
    {
        string playerName = index < playerNames.Length ? playerNames[index] : $"TestPlayer{index + 1}";
        WeaponItem weapon = GetRandomTestWeapon();

        CombatDataTransfer.TeamCharacterCombatData playerData;

        // Create different character archetypes with varying movement speeds
        switch (index)
        {
            case 0: // Fast character - Very High Dexterity (Movement Speed ~45)
                playerData = new CombatDataTransfer.TeamCharacterCombatData
                {
                    characterName = playerName,
                    maxHealth = 18,
                    currentHealth = 18,
                    armorClass = 13,
                    equippedWeapon = weapon?.itemName ?? "Sword",
                    equippedWeaponItem = weapon,
                    strength = 12,
                    dexterity = 25, // Very High DEX = Very Fast movement (MovementSpeed = 30 + 15 = 45)
                    constitution = 14,
                    wisdom = 12,
                    perception = 16,
                    miscItems = CreateTestInventory(index)
                };
                if (showDebugLogs)
                    Debug.Log($"🧪 Created FAST character: {playerName} - DEX:25 (Expected MovementSpeed: 45)");
                break;

            case 1: // Slow character - Very Low Dexterity (Movement Speed ~15)
                playerData = new CombatDataTransfer.TeamCharacterCombatData
                {
                    characterName = playerName,
                    maxHealth = 25,
                    currentHealth = 25,
                    armorClass = 11,
                    equippedWeapon = weapon?.itemName ?? "Sword",
                    equippedWeaponItem = weapon,
                    strength = 16,
                    dexterity = 1, // Very Low DEX = Very Slow movement (MovementSpeed = 30 + (-10) = 20, but formula should give us ~15)
                    constitution = 16,
                    wisdom = 14,
                    perception = 10,
                    miscItems = CreateTestInventory(index)
                };
                if (showDebugLogs)
                    Debug.Log($"🧪 Created SLOW character: {playerName} - DEX:1 (Expected MovementSpeed: ~15)");
                break;

            default: // Balanced character for any additional characters
                playerData = new CombatDataTransfer.TeamCharacterCombatData
                {
                    characterName = playerName,
                    maxHealth = 22,
                    currentHealth = 22,
                    armorClass = 12,
                    equippedWeapon = weapon?.itemName ?? "Sword",
                    equippedWeaponItem = weapon,
                    strength = 14,
                    dexterity = 14, // Average DEX = Average movement (MovementSpeed = 30 + 4*5 = 50)
                    constitution = 14,
                    wisdom = 12,
                    perception = 12,
                    miscItems = CreateTestInventory(index)
                };
                if (showDebugLogs)
                    Debug.Log($"🧪 Created BALANCED character: {playerName} - DEX:14 (Expected MovementSpeed: 50)");
                break;
        }

        if (showDebugLogs)
            Debug.Log($"🧪 Created test player: {playerName} (HP: {playerData.maxHealth}, AC: {playerData.armorClass}, Weapon: {playerData.equippedWeapon})");

        return playerData;
    }

    /// <summary>
    /// Create test enemy character data
    /// </summary>
    CombatDataTransfer.EnemyCombatData CreateTestEnemyData(int index)
    {
        string enemyName = index < enemyNames.Length ? enemyNames[index] : $"TestEnemy{index + 1}";
        WeaponItem weapon = GetRandomTestWeapon();

        var enemyData = new CombatDataTransfer.EnemyCombatData
        {
            enemyName = enemyName,
            maxHealth = baseEnemyHealth + Random.Range(-3, 8),
            armorClass = baseArmorClass + Random.Range(-2, 2),
            preferredWeapon = weapon?.itemName ?? "Fists",
            preferredWeaponItem = weapon,
            threatLevel = Random.Range(1, 6)
        };

        // Set current health to max health
        enemyData.currentHealth = enemyData.maxHealth;

        if (showDebugLogs)
            Debug.Log($"🧪 Created test enemy: {enemyName} (HP: {enemyData.maxHealth}, AC: {enemyData.armorClass}, Weapon: {enemyData.preferredWeapon}, Threat: {enemyData.threatLevel})");

        return enemyData;
    }

    /// <summary>
    /// Create legacy battle setup data for backward compatibility
    /// </summary>
    void CreateTestBattleSetupData()
    {
        // Populate legacy data from the combat session
        CombatDataTransfer.PopulateLegacyBattleSetupData();

        if (showDebugLogs)
            Debug.Log($"🧪 Populated legacy battle setup data: {BattleSetupData.playerSelections.Count} players, {BattleSetupData.enemySelections.Count} enemies");
    }

    /// <summary>
    /// Get a random weapon from available test weapons
    /// </summary>
    WeaponItem GetRandomTestWeapon()
    {
        if (testWeapons == null || testWeapons.Length == 0)
            return null;

        return testWeapons[Random.Range(0, testWeapons.Length)];
    }

    /// <summary>
    /// Create a test inventory with varied items for each character
    /// </summary>
    List<string> CreateTestInventory(int characterIndex)
    {
        var inventory = new List<string>();

        // Base items all characters get
        inventory.Add("Health Potion");
        inventory.Add("Bread");

        // Varied items based on character index
        switch (characterIndex % 4)
        {
            case 0: // Fighter-type
                inventory.Add("Health Potion"); // Extra healing
                inventory.Add("Bandage");
                inventory.Add("Iron Ration");
                break;
            case 1: // Rogue-type
                inventory.Add("Thieves' Tools");
                inventory.Add("Rope");
                inventory.Add("Antidote");
                break;
            case 2: // Mage-type
                inventory.Add("Spell Component");
                inventory.Add("Scroll of Identify");
                inventory.Add("Magic Ink");
                break;
            case 3: // Cleric-type
                inventory.Add("Holy Water");
                inventory.Add("Bandage");
                inventory.Add("Blessed Bread");
                break;
        }

        // Random bonus items
        var bonusItems = new[] { "Torch", "Trail Rations", "Blanket", "Waterskin", "Flint and Steel" };
        int bonusCount = Random.Range(1, 3);
        for (int i = 0; i < bonusCount; i++)
        {
            string bonusItem = bonusItems[Random.Range(0, bonusItems.Length)];
            if (!inventory.Contains(bonusItem))
                inventory.Add(bonusItem);
        }

        return inventory;
    }

    /// <summary>
    /// Log all enhanced test data for debugging
    /// </summary>
    void LogEnhancedTestData()
    {
        Debug.Log("🧪 === Enhanced Test Battle Data ===");

        var session = CombatDataTransfer.GetCurrentSession();
        if (session != null)
        {
            Debug.Log($"🧪 Battle Context: {session.battleTerrain} terrain, {session.weather} weather, {session.timeOfDay:F1}h");

            Debug.Log($"🧪 Players ({session.playerTeam.Count}):");
            foreach (var player in session.playerTeam)
            {
                Debug.Log($"🧪   - {player.characterName}: HP {player.currentHealth}/{player.maxHealth}, AC {player.armorClass}, Weapon: {player.equippedWeapon}");
            }

            Debug.Log($"🧪 Enemies ({session.enemies.Count}):");
            foreach (var enemy in session.enemies)
            {
                Debug.Log($"🧪   - {enemy.enemyName}: HP {enemy.currentHealth}/{enemy.maxHealth}, AC {enemy.armorClass}, Weapon: {enemy.preferredWeapon}, Threat: {enemy.threatLevel}");
            }
        }

        Debug.Log("🧪 ====================================");
    }

    /// <summary>
    /// Context menu method to manually create enhanced test data
    /// </summary>
    [ContextMenu("Create Enhanced Test Data")]
    public void ManualCreateEnhancedTestData()
    {
        CreateEnhancedTestData();
    }

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

        if (showDebugLogs)
            Debug.Log("🧪 EnhancedBattleTestMode: All test data cleared");
    }

    /// <summary>
    /// Create a balanced test battle
    /// </summary>
    [ContextMenu("Create Balanced Test Battle")]
    public void CreateBalancedTestBattle()
    {
        testPlayerCount = 2;
        testEnemyCount = 2;
        testTerrain = TerrainType.Plains;
        testWeather = Weather.Clear;
        testTimeOfDay = 14f;

        CreateEnhancedTestData();
    }

    /// <summary>
    /// Create a challenging test battle
    /// </summary>
    [ContextMenu("Create Challenging Test Battle")]
    public void CreateChallengingTestBattle()
    {
        testPlayerCount = 2;
        testEnemyCount = 4;
        baseEnemyHealth = 20; // Tougher enemies
        testTerrain = TerrainType.Plains;
        testWeather = Weather.Storm;
        testTimeOfDay = 22f; // Night battle

        CreateEnhancedTestData();

        // Reset values
        baseEnemyHealth = 15;
    }

    /// <summary>
    /// Create a simple test battle for quick testing
    /// </summary>
    [ContextMenu("Create Simple Test Battle")]
    public void CreateSimpleTestBattle()
    {
        testPlayerCount = 1;
        testEnemyCount = 1;
        testTerrain = TerrainType.Plains;
        testWeather = Weather.Clear;
        testTimeOfDay = 12f;

        CreateEnhancedTestData();
    }
}
