using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Automatic setup script for the Combat Scene Integration system
/// Run this in the Unity Editor to quickly set up the system in your scenes
/// </summary>
public class CombatIntegrationSetup : MonoBehaviour
{
    [Header("Setup Configuration")]
    [Tooltip("The name of your battle scene")]
    public string battleSceneName = "BattleScene";

    [Tooltip("Enable debug logging for all components")]
    public bool enableDebugLogs = true;

    [Header("Setup Actions")]
    [Tooltip("Set up the map scene with CombatSceneManager")]
    public bool setupMapScene = true;

    [Tooltip("Set up the battle scene with EnhancedBattleSetup")]
    public bool setupBattleScene = true;

    [Header("UI Setup")]
    [Tooltip("Create a battle context UI text element")]
    public bool createBattleContextUI = true;

    [Tooltip("Font size for the battle context text")]
    public int contextTextFontSize = 18;

    /// <summary>
    /// Set up the entire combat integration system
    /// </summary>
    [ContextMenu("Setup Combat Integration System")]
    public void SetupSystem()
    {
        Debug.Log("🔧 Setting up Combat Integration System...");

        string currentScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;

        if (setupMapScene && IsMapScene(currentScene))
        {
            SetupMapSceneComponents();
        }

        if (setupBattleScene && IsBattleScene(currentScene))
        {
            SetupBattleSceneComponents();
        }

        Debug.Log("✅ Combat Integration System setup complete!");
        Debug.Log("📖 See COMBAT_SCENE_INTEGRATION_GUIDE.md for usage instructions");
    }

    /// <summary>
    /// Set up components needed in the map scene
    /// </summary>
    [ContextMenu("Setup Map Scene")]
    public void SetupMapSceneComponents()
    {
        Debug.Log("🗺️ Setting up map scene components...");

        // 1. Find or create CombatSceneManager
        var existingManager = FindFirstObjectByType<CombatSceneManager>();
        if (existingManager == null)
        {
            GameObject managerObj = new GameObject("CombatSceneManager");
            var manager = managerObj.AddComponent<CombatSceneManager>();

            // Configure the manager
            SetManagerProperties(manager);

            Debug.Log("✅ Created CombatSceneManager");
        }
        else
        {
            SetManagerProperties(existingManager);
            Debug.Log("✅ Found and configured existing CombatSceneManager");
        }

        // 2. Verify CombatEventIntegration exists
        var combatIntegration = FindFirstObjectByType<CombatEventIntegration>();
        if (combatIntegration == null)
        {
            Debug.LogWarning("⚠️ No CombatEventIntegration found in scene - please ensure it's set up for combat events to work");
        }
        else
        {
            Debug.Log("✅ Found CombatEventIntegration");
        }

        // 3. Check for terrain generator
        var terrainGen = FindFirstObjectByType<BFMTerrainGenerator>();
        if (terrainGen == null)
        {
            Debug.LogWarning("⚠️ No BFMTerrainGenerator found - terrain effects will be limited");
        }
        else
        {
            Debug.Log("✅ Found BFMTerrainGenerator");
        }
    }

    /// <summary>
    /// Set up components needed in the battle scene
    /// </summary>
    [ContextMenu("Setup Battle Scene")]
    public void SetupBattleSceneComponents()
    {
        Debug.Log("⚔️ Setting up battle scene components...");

        // 1. Find existing BattleSetup
        var battleSetup = FindFirstObjectByType<BattleSetup>();
        if (battleSetup == null)
        {
            Debug.LogError("❌ No BattleSetup component found in scene! Please ensure you're in the correct battle scene.");
            return;
        }

        // 2. Add EnhancedBattleSetup if not present
        var enhancedSetup = battleSetup.GetComponent<EnhancedBattleSetup>();
        if (enhancedSetup == null)
        {
            enhancedSetup = battleSetup.gameObject.AddComponent<EnhancedBattleSetup>();
            Debug.Log("✅ Added EnhancedBattleSetup component");
        }
        else
        {
            Debug.Log("✅ Found existing EnhancedBattleSetup component");
        }

        // Configure enhanced setup
        SetEnhancedSetupProperties(enhancedSetup);

        // 3. Set up terrain generator
        var terrainGen = FindFirstObjectByType<BFMTerrainGenerator>();
        if (terrainGen == null)
        {
            Debug.LogWarning("⚠️ No BFMTerrainGenerator found in battle scene - terrain setup will be skipped");
        }
        else
        {
            enhancedSetup.terrainGenerator = terrainGen;
            Debug.Log("✅ Connected BFMTerrainGenerator to EnhancedBattleSetup");
        }

        // 4. Set up battle context UI if requested
        if (createBattleContextUI)
        {
            SetupBattleContextUI(enhancedSetup);
        }
    }

    /// <summary>
    /// Configure CombatSceneManager properties
    /// </summary>
    private void SetManagerProperties(CombatSceneManager manager)
    {
        if (manager == null) return;

        // Use reflection to set properties since we might have compilation issues
        var type = manager.GetType();

        // Set battle scene name
        var battleSceneField = type.GetField("battleSceneName");
        if (battleSceneField != null)
        {
            battleSceneField.SetValue(manager, battleSceneName);
        }

        // Set debug logs
        var debugField = type.GetField("showDebugLogs");
        if (debugField != null)
        {
            debugField.SetValue(manager, enableDebugLogs);
        }

        Debug.Log($"📝 Configured CombatSceneManager: scene='{battleSceneName}', debug={enableDebugLogs}");
    }

    /// <summary>
    /// Configure EnhancedBattleSetup properties
    /// </summary>
    private void SetEnhancedSetupProperties(EnhancedBattleSetup enhancedSetup)
    {
        if (enhancedSetup == null) return;

        var type = enhancedSetup.GetType();

        // Enable enhanced setup
        var useEnhancedField = type.GetField("useEnhancedSetup");
        if (useEnhancedField != null)
        {
            useEnhancedField.SetValue(enhancedSetup, true);
        }

        // Set debug logs
        var debugField = type.GetField("showDebugLogs");
        if (debugField != null)
        {
            debugField.SetValue(enhancedSetup, enableDebugLogs);
        }

        Debug.Log($"📝 Configured EnhancedBattleSetup: enhanced=true, debug={enableDebugLogs}");
    }

    /// <summary>
    /// Set up battle context UI
    /// </summary>
    private void SetupBattleContextUI(EnhancedBattleSetup enhancedSetup)
    {
        // Look for existing Canvas
        Canvas canvas = FindFirstObjectByType<Canvas>();
        if (canvas == null)
        {
            Debug.LogWarning("⚠️ No Canvas found - cannot create battle context UI");
            return;
        }

        // Check if battle context text already exists
        Transform existingText = canvas.transform.Find("BattleContextText");
        if (existingText != null)
        {
            var existingTextComp = existingText.GetComponent<Text>();
            if (existingTextComp != null)
            {
                AssignBattleContextText(enhancedSetup, existingTextComp);
                Debug.Log("✅ Found and assigned existing BattleContextText");
                return;
            }
        }

        // Create new battle context UI
        GameObject textObj = new GameObject("BattleContextText");
        textObj.transform.SetParent(canvas.transform, false);

        // Add Text component
        Text textComponent = textObj.AddComponent<Text>();
        textComponent.text = "Battle Context Will Appear Here";
        textComponent.fontSize = contextTextFontSize;
        textComponent.color = Color.white;
        textComponent.alignment = TextAnchor.UpperCenter;

        // Try to assign a font
        textComponent.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

        // Position at top of screen
        RectTransform rectTransform = textComponent.GetComponent<RectTransform>();
        rectTransform.anchorMin = new Vector2(0, 1);
        rectTransform.anchorMax = new Vector2(1, 1);
        rectTransform.pivot = new Vector2(0.5f, 1);
        rectTransform.offsetMin = new Vector2(10, -100);
        rectTransform.offsetMax = new Vector2(-10, -10);

        // Assign to enhanced setup
        AssignBattleContextText(enhancedSetup, textComponent);

        Debug.Log("✅ Created BattleContextText UI element");
    }

    /// <summary>
    /// Assign battle context text to enhanced setup using reflection
    /// </summary>
    private void AssignBattleContextText(EnhancedBattleSetup enhancedSetup, Text textComponent)
    {
        var type = enhancedSetup.GetType();
        var textField = type.GetField("battleContextText");
        if (textField != null)
        {
            textField.SetValue(enhancedSetup, textComponent);
            Debug.Log("📝 Assigned battle context text to EnhancedBattleSetup");
        }
    }

    /// <summary>
    /// Check if current scene is a map scene
    /// </summary>
    private bool IsMapScene(string sceneName)
    {
        return sceneName.ToLower().Contains("map") ||
               sceneName.ToLower().Contains("travel") ||
               sceneName.ToLower().Contains("world");
    }

    /// <summary>
    /// Check if current scene is a battle scene
    /// </summary>
    private bool IsBattleScene(string sceneName)
    {
        return sceneName.ToLower().Contains("battle") ||
               sceneName.ToLower().Contains("combat") ||
               sceneName.ToLower().Contains("fight");
    }

    /// <summary>
    /// Validate the current setup
    /// </summary>
    [ContextMenu("Validate Setup")]
    public void ValidateSetup()
    {
        Debug.Log("🔍 Validating Combat Integration Setup...");

        string currentScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
        bool isValid = true;

        if (IsMapScene(currentScene))
        {
            isValid &= ValidateMapScene();
        }
        else if (IsBattleScene(currentScene))
        {
            isValid &= ValidateBattleScene();
        }
        else
        {
            Debug.LogWarning($"⚠️ Unknown scene type: {currentScene}");
        }

        if (isValid)
        {
            Debug.Log("✅ Setup validation passed!");
        }
        else
        {
            Debug.LogWarning("⚠️ Setup validation found issues - see messages above");
        }
    }

    /// <summary>
    /// Validate map scene setup
    /// </summary>
    private bool ValidateMapScene()
    {
        bool valid = true;

        // Check CombatSceneManager
        var manager = FindFirstObjectByType<CombatSceneManager>();
        if (manager == null)
        {
            Debug.LogError("❌ CombatSceneManager not found in map scene");
            valid = false;
        }
        else
        {
            Debug.Log("✅ CombatSceneManager found");
        }

        // Check CombatEventIntegration
        var integration = FindFirstObjectByType<CombatEventIntegration>();
        if (integration == null)
        {
            Debug.LogWarning("⚠️ CombatEventIntegration not found - combat events may not work");
        }
        else
        {
            Debug.Log("✅ CombatEventIntegration found");
        }

        return valid;
    }

    /// <summary>
    /// Validate battle scene setup
    /// </summary>
    private bool ValidateBattleScene()
    {
        bool valid = true;

        // Check BattleSetup
        var battleSetup = FindFirstObjectByType<BattleSetup>();
        if (battleSetup == null)
        {
            Debug.LogError("❌ BattleSetup not found in battle scene");
            valid = false;
        }
        else
        {
            Debug.Log("✅ BattleSetup found");

            // Check EnhancedBattleSetup
            var enhancedSetup = battleSetup.GetComponent<EnhancedBattleSetup>();
            if (enhancedSetup == null)
            {
                Debug.LogWarning("⚠️ EnhancedBattleSetup not found - enhanced features will not work");
            }
            else
            {
                Debug.Log("✅ EnhancedBattleSetup found");
            }
        }

        return valid;
    }

    /// <summary>
    /// Clean up this setup script (remove it after setup is complete)
    /// </summary>
    [ContextMenu("Remove Setup Script")]
    public void RemoveSetupScript()
    {
        Debug.Log("🧹 Removing CombatIntegrationSetup script...");
        DestroyImmediate(this);
    }
}
