using UnityEngine;
using UnityEngine.UIElements;

/// <summary>
/// Setup script to configure the new travel system in the map scene.
/// This script automatically sets up the travel system components and ensures proper integration.
/// </summary>
public class TravelSystemSetup : MonoBehaviour
{
    [Header("Setup Options")]
    public bool autoSetupOnStart = true;
    public bool showDebugLogs = true;

    [Header("Travel System Settings")]
    [Range(0.1f, 5f)]
    public float plainsMovementCost = 1f;
    [Range(0.1f, 5f)]
    public float forestMovementCost = 2f;
    [Range(0.1f, 5f)]
    public float mountainMovementCost = 4f;
    [Range(0.1f, 2f)]
    public float roadMovementCost = 0.5f;
    [Range(0.1f, 2f)]
    public float townMovementCost = 0.1f;

    [Header("Visual Settings")]
    public Material pathLineMaterial;
    public Color standardPathColor = Color.blue;
    public Color expensivePathColor = Color.red;
    [Range(0.1f, 1f)]
    public float pathLineWidth = 0.2f;

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

    [ContextMenu("Setup Travel System")]
    public void SetupTravelSystem()
    {
        if (showDebugLogs)
        {
            Debug.Log("🔧 Setting up Travel System...");
        }

        // 1. Create TeamTravelSystem if it doesn't exist
        SetupTeamTravelSystem();

        // 2. Setup TravelUIController if UI exists
        SetupTravelUIController();

        // 2.5. Setup TravelUI component
        SetupTravelUIComponent();

        // 3. Verify SimpleTeamPlacement integration
        VerifyTeamPlacementIntegration();

        if (showDebugLogs)
        {
            Debug.Log("✅ Travel System setup complete!");
        }
    }

    private void SetupTeamTravelSystem()
    {
        var existingTravelSystem = FindFirstObjectByType<TeamTravelSystem>();

        if (existingTravelSystem == null)
        {
            // Create new travel system
            GameObject travelSystemObj = new GameObject("TeamTravelSystem");
            var travelSystem = travelSystemObj.AddComponent<TeamTravelSystem>();

            // Apply settings
            travelSystem.plainsMovementCost = plainsMovementCost;
            travelSystem.forestMovementCost = forestMovementCost;
            travelSystem.mountainMovementCost = mountainMovementCost;
            travelSystem.roadMovementCost = roadMovementCost;
            travelSystem.townMovementCost = townMovementCost;
            travelSystem.pathLineMaterial = pathLineMaterial;
            travelSystem.standardPathColor = standardPathColor;
            travelSystem.expensivePathColor = expensivePathColor;
            travelSystem.pathLineWidth = pathLineWidth;
            travelSystem.showDebugLogs = showDebugLogs;

            if (showDebugLogs)
            {
                Debug.Log("📦 Created TeamTravelSystem component");
            }
        }
        else
        {
            if (showDebugLogs)
            {
                Debug.Log("✅ TeamTravelSystem already exists");
            }
        }
    }

    private void SetupTravelUIController()
    {
        // Look for UI GameObject
        GameObject uiGameObject = GameObject.Find("UI");
        if (uiGameObject == null)
        {
            if (showDebugLogs)
            {
                Debug.Log("⚠️ No UI GameObject found - TravelUIController not setup");
            }
            return;
        }

        var existingUIController = uiGameObject.GetComponent<TravelUIController>();

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

            if (showDebugLogs)
            {
                Debug.Log("📦 Added TravelUIController to UI GameObject");
            }
        }
        else
        {
            if (showDebugLogs)
            {
                Debug.Log("✅ TravelUIController already exists");
            }
        }
    }

    /// <summary>
    /// Sets up the TravelUI component to handle the travel interface
    /// </summary>
    private void SetupTravelUIComponent()
    {
        // Check if TravelUI exists
        var travelUI = FindFirstObjectByType<TravelUI>();
        if (travelUI == null)
        {
            // Create TravelUI GameObject
            GameObject travelUIGameObject = new GameObject("TravelUI");
            var uiDocument = travelUIGameObject.AddComponent<UIDocument>();
            var travelUIComponent = travelUIGameObject.AddComponent<TravelUI>();
            travelUIComponent.uiDocument = uiDocument;

            // Try to load and assign the TravelUI.uxml file
            var travelUIAsset = Resources.Load<VisualTreeAsset>("UI/Map/TravelUI");
            if (travelUIAsset != null)
            {
                uiDocument.visualTreeAsset = travelUIAsset;
                travelUIComponent.travelUIAsset = travelUIAsset;
                if (showDebugLogs)
                {
                    Debug.Log("✅ Assigned TravelUI.uxml to new TravelUI component");
                }
            }
            else
            {
                Debug.LogWarning("⚠️ Could not find TravelUI.uxml in Resources/UI/Map/");
            }

            if (showDebugLogs)
            {
                Debug.Log("📦 Created TravelUI GameObject with component");
            }
        }
        else
        {
            // Ensure existing TravelUI has proper UXML assigned
            var uiDocument = travelUI.uiDocument;
            if (uiDocument != null && (uiDocument.visualTreeAsset == null || travelUI.travelUIAsset == null))
            {
                var travelUIAsset = Resources.Load<VisualTreeAsset>("UI/Map/TravelUI");
                if (travelUIAsset != null)
                {
                    uiDocument.visualTreeAsset = travelUIAsset;
                    travelUI.travelUIAsset = travelUIAsset;
                    if (showDebugLogs)
                    {
                        Debug.Log("✅ Assigned TravelUI.uxml to existing TravelUI component");
                    }
                }
            }

            if (showDebugLogs)
            {
                Debug.Log("✅ TravelUI component already exists and is properly configured");
            }
        }
    }

    private void VerifyTeamPlacementIntegration()
    {
        var teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();

        if (teamPlacement == null)
        {
            if (showDebugLogs)
            {
                Debug.LogWarning("⚠️ SimpleTeamPlacement not found - travel system may not work properly");
            }
            return;
        }

        if (showDebugLogs)
        {
            Debug.Log("✅ SimpleTeamPlacement found and ready for integration");
        }
    }

    [ContextMenu("Show Travel System Status")]
    public void ShowTravelSystemStatus()
    {
        Debug.Log("=== TRAVEL SYSTEM STATUS ===");

        var travelSystem = FindFirstObjectByType<TeamTravelSystem>();
        Debug.Log($"TeamTravelSystem: {(travelSystem != null ? "✅ Found" : "❌ Missing")}");

        var uiController = FindFirstObjectByType<TravelUIController>();
        Debug.Log($"TravelUIController: {(uiController != null ? "✅ Found" : "❌ Missing")}");

        var teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
        Debug.Log($"SimpleTeamPlacement: {(teamPlacement != null ? "✅ Found" : "❌ Missing")}");

        var mapMaker = FindFirstObjectByType<MapMaker2>();
        Debug.Log($"MapMaker2: {(mapMaker != null ? "✅ Found" : "❌ Missing")}");

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

    [ContextMenu("Test Travel Planning")]
    public void TestTravelPlanning()
    {
        var travelSystem = FindFirstObjectByType<TeamTravelSystem>();
        var teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();

        if (travelSystem == null || teamPlacement == null)
        {
            Debug.LogError("❌ Cannot test travel planning - missing components");
            return;
        }

        if (!teamPlacement.IsTeamPlaced())
        {
            Debug.LogError("❌ Cannot test travel planning - team not placed");
            return;
        }

        // Plan travel to a random nearby position
        Vector2Int currentPos = teamPlacement.GetTeamPosition();
        Vector2Int testDestination = new Vector2Int(currentPos.x + 10, currentPos.y + 10);

        travelSystem.PlanTravelTo(testDestination);

        Debug.Log($"🧪 Test travel planning from {currentPos} to {testDestination}");
    }
}
