using UnityEngine;
using UnityEngine.UIElements;

/// <summary>
/// Setup script to configure all UI systems in the map scene.
/// Handles both travel system and team overview setup automatically.
/// </summary>
public class MapSceneSetup : MonoBehaviour
{
    [Header("Setup Options")]
    public bool autoSetupOnStart = true;
    public bool showDebugLogs = true;

    [Header("UI Settings")]
    public bool enableTeamOverview = true;
    public bool enableTravelSystem = true;

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

    [ContextMenu("Setup Map Scene")]
    public void SetupMapScene()
    {
        // Check if we're in Play Mode
        if (!Application.isPlaying)
        {
            Debug.LogWarning("⚠️ MapSceneSetup: Please run this setup during Play Mode, not Edit Mode!");
            Debug.LogWarning("💡 Either enter Play Mode and try again, or let it run automatically via autoSetupOnStart.");
            return;
        }

        if (showDebugLogs)
        {
            Debug.Log("🏗️ Setting up Map Scene UI systems...");
        }

        // Setup team overview if enabled
        if (enableTeamOverview)
        {
            SetupTeamOverview();
        }

        // Setup travel system if enabled
        if (enableTravelSystem)
        {
            SetupTravelSystem();
        }

        if (showDebugLogs)
        {
            Debug.Log("✅ Map Scene setup complete!");
        }
    }

    [ContextMenu("Force Setup (Play Mode Only)")]
    public void ForceSetupInPlayMode()
    {
        if (!Application.isPlaying)
        {
            Debug.LogError("❌ This setup requires Play Mode! Enter Play Mode first.");
            return;
        }

        SetupMapScene();
    }

    /// <summary>
    /// Sets up the team overview controller
    /// </summary>
    private void SetupTeamOverview()
    {
        // Look for UI GameObject
        GameObject uiGameObject = GameObject.Find("UI");
        if (uiGameObject == null)
        {
            if (showDebugLogs)
            {
                Debug.LogWarning("⚠️ No UI GameObject found - Team Overview not setup");
            }
            return;
        }

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

        // Create a new GameObject for the TeamOverviewController
        GameObject teamOverviewObject = new GameObject("TeamOverviewController");
        teamOverviewObject.transform.SetParent(uiGameObject.transform);

        // Add the TeamOverviewController component
        var teamOverviewController = teamOverviewObject.AddComponent<TeamOverviewController>();

        if (showDebugLogs)
        {
            Debug.Log("✅ TeamOverviewController created and setup");
        }
    }

    /// <summary>
    /// Sets up the travel system (delegates to existing setup if available)
    /// </summary>
    private void SetupTravelSystem()
    {
        var travelSystemSetup = FindFirstObjectByType<TravelSystemSetup>();
        if (travelSystemSetup != null)
        {
            if (showDebugLogs)
            {
                Debug.Log("🚗 Using existing TravelSystemSetup");
            }
            // Let the existing travel system setup handle this
            return;
        }

        // Look for UI GameObject
        GameObject uiGameObject = GameObject.Find("UI");
        if (uiGameObject == null)
        {
            if (showDebugLogs)
            {
                Debug.LogWarning("⚠️ No UI GameObject found - Travel System not setup");
            }
            return;
        }

        // Check if TravelUIController already exists
        var existingUIController = uiGameObject.GetComponent<TravelUIController>();
        if (existingUIController != null)
        {
            if (showDebugLogs)
            {
                Debug.Log("🚗 TravelUIController already exists");
            }
            return;
        }

        // Add TravelUIController to UI GameObject
        var uiController = uiGameObject.AddComponent<TravelUIController>();
        uiController.showDebugLogs = showDebugLogs;

        if (showDebugLogs)
        {
            Debug.Log("✅ TravelUIController created and setup");
        }
    }

    /// <summary>
    /// Context menu methods for debugging
    /// </summary>
    [ContextMenu("Setup Team Overview Only")]
    public void SetupTeamOverviewOnly()
    {
        SetupTeamOverview();
    }

    [ContextMenu("Setup Travel System Only")]
    public void SetupTravelSystemOnly()
    {
        SetupTravelSystem();
    }

    [ContextMenu("Verify UI Setup")]
    public void VerifyUISetup()
    {
        var uiGameObject = GameObject.Find("UI");
        if (uiGameObject == null)
        {
            Debug.LogError("❌ UI GameObject not found!");
            return;
        }

        var uiDocument = uiGameObject.GetComponent<UIDocument>();
        var teamOverviewController = FindFirstObjectByType<TeamOverviewController>();
        var travelUIController = uiGameObject.GetComponent<TravelUIController>();

        Debug.Log($"🔍 UI Setup Verification:");
        Debug.Log($"   UIDocument: {(uiDocument != null ? "✅" : "❌")}");
        Debug.Log($"   TeamOverviewController: {(teamOverviewController != null ? "✅" : "❌")}");
        Debug.Log($"   TravelUIController: {(travelUIController != null ? "✅" : "❌")}");

        if (uiDocument?.rootVisualElement != null)
        {
            var root = uiDocument.rootVisualElement;
            var teamOverviewPanel = root.Q("TeamOverviewPanel");
            var travelContainer = root.Q("TravelContainer");

            Debug.Log($"   TeamOverviewPanel in UXML: {(teamOverviewPanel != null ? "✅" : "❌")}");
            Debug.Log($"   TravelContainer in UXML: {(travelContainer != null ? "✅" : "❌")}");
        }
    }
}
