using UnityEngine;
using System.Collections.Generic;

/// <summary>
/// Test script for the Combat Scene Integration system
/// Use this to verify that the system works correctly
/// </summary>
public class CombatIntegrationTest : MonoBehaviour
{
    [Header("Test Configuration")]
    [Tooltip("Test terrain type for combat")]
    public TerrainType testTerrain = TerrainType.Forest;

    [Tooltip("Test feature type")]
    public FeatureType testFeature = FeatureType.Road;

    [Tooltip("Number of test enemies")]
    public int testEnemyCount = 2;

    [Tooltip("Test enemy type name")]
    public string testEnemyType = "Test Bandit";

    [Header("Test Controls")]
    [Tooltip("Enable this to run test combat on Start - Creates FastRogue (DEX:20) and SlowTank (DEX:4)")]
    public bool runTestOnStart = false;

    void Start()
    {
        if (runTestOnStart)
        {
            // Delay the test slightly to ensure scene is fully loaded
            Invoke(nameof(RunCombatTest), 1f);
        }
    }

    /// <summary>
    /// Run a test combat scenario
    /// </summary>
    [ContextMenu("Run Combat Test")]
    public void RunCombatTest()
    {
        Debug.Log("🧪 Running combat integration test...");

        // Create test team data
        List<TeamCharacter> testTeam = CreateTestTeam();

        // Create test battle data
        BattleEventData testBattleData = CreateTestBattleData();

        // Create test context
        TravelEventContext testContext = CreateTestContext();

        // Initialize combat session
        CombatDataTransfer.InitializeCombatSession(testBattleData, testContext, testTeam);

        // Debug the session
        CombatDataTransfer.DebugLogSession();

        // Test the CombatSceneManager
        TestCombatSceneManager();

        Debug.Log("✅ Combat integration test complete!");
    }

    /// <summary>
    /// Create test team data with varied movement speeds
    /// </summary>
    private List<TeamCharacter> CreateTestTeam()
    {
        List<TeamCharacter> team = new List<TeamCharacter>();

        // Create a FAST character - Very High Dexterity
        var fastRogue = new TeamCharacter
        {
            name = "FastRogue",
            isMale = true,
            strength = 12,
            dexterity = 25, // Very High DEX = Very Fast movement (MovementSpeed = 30 + 15 = 45)
            constitution = 14,
            wisdom = 12,
            perception = 16,
            gold = 50,
            silver = 25,
            copper = 10,
            equippedWeapon = "Sword",
            equippedArmor = "Leather Armor",
            weapons = new List<string> { "Sword", "Bow" },
            armor = new List<string> { "Leather Armor" }
        };
        team.Add(fastRogue);

        // Create a SLOW character - Very Low Dexterity
        var slowTank = new TeamCharacter
        {
            name = "SlowTank",
            isMale = false,
            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,
            gold = 45,
            silver = 30,
            copper = 5,
            equippedWeapon = "Sword",
            equippedArmor = "Plate Armor",
            weapons = new List<string> { "Sword", "Mace" },
            armor = new List<string> { "Plate Armor" }
        };
        team.Add(slowTank);

        Debug.Log($"🏷️ Created test team with {team.Count} members - FastRogue (DEX:25) and SlowTank (DEX:1)");
        return team;
    }

    /// <summary>
    /// Create test battle data
    /// </summary>
    private BattleEventData CreateTestBattleData()
    {
        var battleData = new BattleEventData
        {
            enemyCount = testEnemyCount,
            enemyType = testEnemyType,
            battleDescription = $"A test encounter with {testEnemyCount} {testEnemyType}s",
            enemyCharacterData = null // Could be set to a real EnemyCharacterData asset
        };

        Debug.Log($"⚔️ Created test battle data: {battleData.enemyCount}x {battleData.enemyType}");
        return battleData;
    }

    /// <summary>
    /// Create test travel context
    /// </summary>
    private TravelEventContext CreateTestContext()
    {
        // Create a mock map tile
        var mockTile = new MapTile(0, 0)
        {
            terrainType = testTerrain,
            featureType = testFeature
        };

        var context = new TravelEventContext(Vector2Int.zero, mockTile, null)
        {
            dayOfJourney = 3,
            timeOfDay = 14.5f, // 2:30 PM
            currentWeather = Weather.Clear,
            teamGold = 150,
            teamFood = 75,
            teamMorale = 0.8f,
            isOnMainRoad = testFeature == FeatureType.Road,
            distanceToDestination = 25.5f
        };

        Debug.Log($"🌍 Created test context: {testTerrain} terrain, {testFeature} feature");
        return context;
    }

    /// <summary>
    /// Test the CombatSceneManager functionality
    /// </summary>
    private void TestCombatSceneManager()
    {
        // Find CombatSceneManager
        var manager = FindFirstObjectByType<MonoBehaviour>();
        MonoBehaviour combatManager = null;

        // Look for CombatSceneManager by name
        var allComponents = FindObjectsByType<MonoBehaviour>(FindObjectsSortMode.None);
        foreach (var comp in allComponents)
        {
            if (comp.GetType().Name == "CombatSceneManager")
            {
                combatManager = comp;
                break;
            }
        }

        if (combatManager != null)
        {
            Debug.Log("✅ Found CombatSceneManager");

            // Test getting battle context description
            var method = combatManager.GetType().GetMethod("GetBattleContextDescription");
            if (method != null)
            {
                string description = (string)method.Invoke(combatManager, null);
                Debug.Log($"📝 Battle context: {description}");
            }
        }
        else
        {
            Debug.LogWarning("⚠️ CombatSceneManager not found - add it to test scene loading");
        }
    }

    /// <summary>
    /// Test data transfer without scene loading
    /// </summary>
    [ContextMenu("Test Data Transfer Only")]
    public void TestDataTransferOnly()
    {
        Debug.Log("📊 Testing data transfer system...");

        // Create test data
        List<TeamCharacter> testTeam = CreateTestTeam();
        BattleEventData testBattleData = CreateTestBattleData();
        TravelEventContext testContext = CreateTestContext();

        // Test initialization
        CombatDataTransfer.InitializeCombatSession(testBattleData, testContext, testTeam);

        // Test session validity
        bool hasValidSession = CombatDataTransfer.HasValidSession();
        Debug.Log($"🔍 Has valid session: {hasValidSession}");

        // Test getting session data
        var session = CombatDataTransfer.GetCurrentSession();
        if (session != null)
        {
            Debug.Log($"👥 Player team: {session.playerTeam.Count} members");
            Debug.Log($"👹 Enemies: {session.enemies.Count} enemies");
            Debug.Log($"🌍 Terrain: {session.battleTerrain}");
            Debug.Log($"🌤️ Weather: {session.weather}");

            // Test terrain description
            string terrainDesc = CombatDataTransfer.GetTerrainDescription(session.battleTerrain, session.battleFeature);
            Debug.Log($"📝 Terrain description: {terrainDesc}");
        }

        // Test legacy compatibility
        CombatDataTransfer.PopulateLegacyBattleSetupData();
        Debug.Log($"🔧 Legacy data populated: {BattleSetupData.playerSelections.Count} players, {BattleSetupData.enemySelections.Count} enemies");

        // Test cleanup
        CombatDataTransfer.ClearSession();
        Debug.Log($"🧹 Session cleared. Has valid session: {CombatDataTransfer.HasValidSession()}");

        Debug.Log("✅ Data transfer test complete!");
    }

    /// <summary>
    /// Test team data loading from various sources
    /// </summary>
    [ContextMenu("Test Team Data Loading")]
    public void TestTeamDataLoading()
    {
        Debug.Log("👥 Testing team data loading...");

        // Test MainTeamSelectScript
        var teamSelect = FindFirstObjectByType<MainTeamSelectScript>();
        if (teamSelect != null)
        {
            var characters = teamSelect.GetConfiguredCharacters();
            Debug.Log($"📋 MainTeamSelectScript: {characters?.Count ?? 0} characters");
        }
        else
        {
            Debug.Log("📋 MainTeamSelectScript: Not found");
        }

        // Test GameStateManager
        if (GameStateManager.Instance != null && GameStateManager.Instance.savedTeam != null)
        {
            int count = 0;
            foreach (var char_ in GameStateManager.Instance.savedTeam)
            {
                if (char_ != null) count++;
            }
            Debug.Log($"💾 GameStateManager: {count} characters");
        }
        else
        {
            Debug.Log("💾 GameStateManager: Not available or no saved team");
        }

        // Test PlayerPrefs
        int prefCount = 0;
        for (int i = 0; i < 4; i++)
        {
            if (PlayerPrefs.GetInt($"Character{i}_Exists", 0) == 1)
            {
                prefCount++;
            }
        }
        Debug.Log($"🗃️ PlayerPrefs: {prefCount} characters");

        Debug.Log("✅ Team data loading test complete!");
    }

    /// <summary>
    /// Clear test data
    /// </summary>
    [ContextMenu("Clear Test Data")]
    public void ClearTestData()
    {
        CombatDataTransfer.ClearSession();
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();
        Debug.Log("🧹 Test data cleared");
    }
}
