using UnityEngine;
using UnityEngine.UIElements;

/// <summary>
/// Setup script to create and configure the TeamOverview UI system.
/// This creates a separate UI GameObject specifically for the team overview panel.
/// </summary>
public class TeamOverviewSetup : MonoBehaviour
{
    [Header("Setup Options")]
    public bool autoSetupOnStart = true;
    public bool showDebugLogs = true;

    [Header("UI Assets")]
    [SerializeField] private VisualTreeAsset teamOverviewUXML;
    [SerializeField] private StyleSheet teamOverviewStyleSheet;

    void Start()
    {
        if (autoSetupOnStart)
        {
            SetupTeamOverview();
        }
    }

    [ContextMenu("Setup Team Overview UI")]
    public void SetupTeamOverview()
    {
        if (!Application.isPlaying)
        {
            Debug.LogWarning("⚠️ TeamOverviewSetup: Please run this setup during Play Mode!");
            return;
        }

        // Check if TeamOverview already exists
        var existingOverview = FindFirstObjectByType<TeamOverviewController>();
        if (existingOverview != null)
        {
            if (showDebugLogs)
            {
                Debug.Log("📋 TeamOverview already exists, skipping setup");
            }
            return;
        }

        // Try to load UXML asset if not assigned
        if (teamOverviewUXML == null)
        {
            teamOverviewUXML = Resources.Load<VisualTreeAsset>("UI/MapScene/TeamOverview");
            if (teamOverviewUXML == null)
            {
#if UNITY_EDITOR
                // Try alternative paths (Editor only)
                teamOverviewUXML = UnityEditor.AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MapScene/TeamOverview.uxml");
#endif
            }
        }

        if (teamOverviewUXML == null)
        {
            Debug.LogError("❌ TeamOverview.uxml not found! Please assign it in the inspector.");
            return;
        }

        // Create TeamOverview GameObject
        GameObject teamOverviewObject = new GameObject("TeamOverviewUI");
        teamOverviewObject.transform.SetParent(transform);

        // Add UIDocument component
        UIDocument uiDocument = teamOverviewObject.AddComponent<UIDocument>();
        uiDocument.visualTreeAsset = teamOverviewUXML;

        // Find and assign Panel Settings from existing UI
        var existingUI = GameObject.Find("TravelUI")?.GetComponent<UIDocument>();
        if (existingUI?.panelSettings != null)
        {
            uiDocument.panelSettings = existingUI.panelSettings;
            if (showDebugLogs)
            {
                Debug.Log("✅ Panel Settings assigned from TravelUI");
            }
        }
        else
        {
            // Try to find any PanelSettings asset
#if UNITY_EDITOR
            var panelSettings = UnityEditor.AssetDatabase.FindAssets("t:PanelSettings");
            if (panelSettings.Length > 0)
            {
                var path = UnityEditor.AssetDatabase.GUIDToAssetPath(panelSettings[0]);
                var settings = UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.PanelSettings>(path);
                uiDocument.panelSettings = settings;
                if (showDebugLogs)
                {
                    Debug.Log($"✅ Panel Settings auto-assigned: {settings.name}");
                }
            }
#endif
        }

        // Add style sheet if available (the UXML file should reference it automatically)
        if (teamOverviewStyleSheet != null && showDebugLogs)
        {
            Debug.Log("ℹ️ Style sheet will be loaded automatically from UXML reference");
        }

        // Set up the UI to appear on the right side with appropriate priority
        uiDocument.sortingOrder = 5; // Lower than combat popups but higher than map UI

        // Add TeamOverviewController
        TeamOverviewController controller = teamOverviewObject.AddComponent<TeamOverviewController>();
        controller.showDebugLogs = showDebugLogs;

        // Ensure the UI root doesn't block other UI elements
        StartCoroutine(ConfigureUIEventHandling(uiDocument));

        // Position the UI panel on the right side
        StartCoroutine(PositionTeamOverview(uiDocument));

        // Ensure TravelEventUI exists for travel events
        EnsureTravelEventUI();

        // Ensure player object exists for MapMaker2
        EnsurePlayerObject();

        // Ensure combat popups have highest priority
        EnsureCombatPopupPriority();

        if (showDebugLogs)
        {
            Debug.Log("✅ TeamOverview UI created and configured!");
        }
    }

    private System.Collections.IEnumerator PositionTeamOverview(UIDocument uiDocument)
    {
        // Wait a frame for the UI to initialize
        yield return null;

        var root = uiDocument.rootVisualElement;
        var teamPanel = root.Q("TeamOverviewPanel");

        if (teamPanel != null)
        {
            // Position the panel on the right side of the screen
            teamPanel.style.position = Position.Absolute;
            teamPanel.style.right = 10;
            teamPanel.style.top = 10;
            teamPanel.style.width = 300;
            teamPanel.style.height = Length.Percent(80);

            // Make sure it's visible
            teamPanel.style.display = DisplayStyle.Flex;

            // Add TravelUI-style click blocking overlay
            AddClickBlockingOverlay(root);

            if (showDebugLogs)
            {
                Debug.Log("📍 TeamOverview positioned on right side with click blocking overlay");
            }
        }
    }

    private void AddClickBlockingOverlay(VisualElement root)
    {
        // Create a click blocker similar to TravelUI
        var clickBlocker = new VisualElement();
        clickBlocker.name = "ClickBlocker";
        clickBlocker.AddToClassList("click-blocker");

        // Position as first child (behind everything else)
        root.Insert(0, clickBlocker);

        // Block all mouse events
        clickBlocker.RegisterCallback<ClickEvent>(evt =>
        {
            evt.StopPropagation();
        });

        clickBlocker.RegisterCallback<MouseDownEvent>(evt =>
        {
            evt.StopPropagation();
        });

        clickBlocker.RegisterCallback<MouseUpEvent>(evt =>
        {
            evt.StopPropagation();
        });
    }

    private System.Collections.IEnumerator ConfigureUIEventHandling(UIDocument uiDocument)
    {
        // Wait a frame for the UI to initialize
        yield return null;

        var root = uiDocument.rootVisualElement;

        if (root != null)
        {
            // Ensure root doesn't block other UI - set to ignore picking
            root.pickingMode = PickingMode.Ignore;

            if (showDebugLogs)
            {
                Debug.Log("✅ TeamOverview root configured to not interfere with other UI");
            }
        }
    }

    /// <summary>
    /// Ensures TravelEventUI exists in the scene to prevent warnings
    /// </summary>
    private void EnsureTravelEventUI()
    {
        var existingEventUI = FindFirstObjectByType<TravelEventUI>();
        if (existingEventUI == null)
        {
            // Create a simple TravelEventUI GameObject
            GameObject eventUIObject = new GameObject("TravelEventUI");
            eventUIObject.transform.SetParent(transform);
            var travelEventUI = eventUIObject.AddComponent<TravelEventUI>();

            if (showDebugLogs)
            {
                Debug.Log("✅ TravelEventUI created to handle travel event messages");
            }
        }
        else if (showDebugLogs)
        {
            Debug.Log("ℹ️ TravelEventUI already exists");
        }
    }

    /// <summary>
    /// Ensures a basic player object exists for MapMaker2
    /// </summary>
    private void EnsurePlayerObject()
    {
        // Check if a player object exists
        var player = GameObject.FindWithTag("Player");
        if (player == null)
        {
            // Try to find any object that might be the player/team
            var teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
            if (teamPlacement != null)
            {
                // Tag the team placement as Player if it exists
                teamPlacement.gameObject.tag = "Player";
                if (showDebugLogs)
                {
                    Debug.Log("✅ Tagged SimpleTeamPlacement as Player for MapMaker2");
                }
            }
            else
            {
                // Create a simple player marker
                GameObject playerMarker = new GameObject("PlayerMarker");
                playerMarker.tag = "Player";
                if (showDebugLogs)
                {
                    Debug.Log("✅ Created basic Player object for MapMaker2");
                }
            }
        }
        else if (showDebugLogs)
        {
            Debug.Log("ℹ️ Player object already exists");
        }
    }

    /// <summary>
    /// Ensures combat popups have the highest UI priority to prevent black squares
    /// </summary>
    private void EnsureCombatPopupPriority()
    {
        // Find combat popup UI documents and ensure they have highest sorting order
        var combatPopup = FindFirstObjectByType<CombatEventPopup>();
        if (combatPopup != null)
        {
            var popupUIDocument = combatPopup.GetComponent<UIDocument>();
            if (popupUIDocument != null)
            {
                popupUIDocument.sortingOrder = 100; // Highest priority
                if (showDebugLogs)
                {
                    Debug.Log("✅ CombatEventPopup sortingOrder set to 100 (highest priority)");
                }
            }
        }

        var combatPopupUXML = FindFirstObjectByType<CombatEventPopupUXML>();
        if (combatPopupUXML != null)
        {
            var popupUIDocument = combatPopupUXML.GetComponent<UIDocument>();
            if (popupUIDocument != null)
            {
                popupUIDocument.sortingOrder = 100; // Highest priority
                if (showDebugLogs)
                {
                    Debug.Log("✅ CombatEventPopupUXML sortingOrder set to 100 (highest priority)");
                }
            }
        }

        if (showDebugLogs && combatPopup == null && combatPopupUXML == null)
        {
            Debug.Log("ℹ️ No combat popup components found - will be configured when created");
        }
    }

    [ContextMenu("Remove Team Overview")]
    public void RemoveTeamOverview()
    {
        var existingOverview = FindFirstObjectByType<TeamOverviewController>();
        if (existingOverview != null)
        {
            DestroyImmediate(existingOverview.gameObject);
            Debug.Log("🗑️ TeamOverview removed");
        }
        else
        {
            Debug.Log("ℹ️ No TeamOverview found to remove");
        }
    }

    [ContextMenu("Test Team Overview")]
    public void TestTeamOverview()
    {
        var controller = FindFirstObjectByType<TeamOverviewController>();
        if (controller != null)
        {
            controller.TestShowTeamOverview();
        }
        else
        {
            Debug.LogWarning("⚠️ No TeamOverviewController found! Run setup first.");
        }
    }

    [ContextMenu("Fix UI Layering Issues")]
    public void FixUILayering()
    {
        Debug.Log("🔧 Fixing UI layering issues...");

        // Set correct sorting orders for all UI systems
        var teamOverview = FindFirstObjectByType<TeamOverviewController>()?.GetComponent<UIDocument>();
        if (teamOverview != null)
        {
            teamOverview.sortingOrder = 5;
            Debug.Log("✅ TeamOverview sortingOrder: 5");
        }

        var travelUI = GameObject.Find("TravelUI")?.GetComponent<UIDocument>();
        if (travelUI != null)
        {
            travelUI.sortingOrder = 3;
            Debug.Log("✅ TravelUI sortingOrder: 3");
        }

        var combatPopup = FindFirstObjectByType<CombatEventPopup>()?.GetComponent<UIDocument>();
        if (combatPopup != null)
        {
            combatPopup.sortingOrder = 100;
            Debug.Log("✅ CombatEventPopup sortingOrder: 100");
        }

        var combatPopupUXML = FindFirstObjectByType<CombatEventPopupUXML>()?.GetComponent<UIDocument>();
        if (combatPopupUXML != null)
        {
            combatPopupUXML.sortingOrder = 100;
            Debug.Log("✅ CombatEventPopupUXML sortingOrder: 100");
        }

        Debug.Log("🎯 UI layering fixed! Combat popups should now appear on top.");
    }
}
