using UnityEngine;
using UnityEngine.UIElements;
#if UNITY_EDITOR
using UnityEditor;
#endif

/// <summary>
/// This script helps set up the shop/inventory system.
/// Attach this to a GameObject in your scene to get started with the shop system.
/// </summary>
public class ShopSystemSetup : MonoBehaviour
{
    [Header("Instructions")]
    [TextArea(5, 10)]
    public string instructions = @"Setup Instructions:
1. Create a GameObject and attach SimpleShopManager script
2. Create a UI Document with ShopUI.uxml as the Visual Tree Asset
3. Attach the UI Document to the same GameObject as SimpleShopManager
4. The shop will automatically populate with default items
5. Click 'Add Weapon', 'Add Armor', or 'Add Misc' buttons in character inventory to open shop";

    [Header("Quick Setup")]
    [SerializeField] private bool createShopGameObject = false;

    [Header("Manual Assignment")]
    [SerializeField] private VisualTreeAsset shopUIAsset;

    [Header("Testing")]
    [SerializeField] private bool testShopSystem = false;
    [SerializeField] private bool debugShopSetup = false;
    [SerializeField] private bool createPanelSettings = false;

    void Update()
    {
        // Handle inspector button presses
        if (testShopSystem)
        {
            testShopSystem = false;
            TestShopSystem();
        }

        if (debugShopSetup)
        {
            debugShopSetup = false;
            DebugShopSetup();
        }

        if (createPanelSettings)
        {
            createPanelSettings = false;
            CreatePanelSettings();
        }
    }

    [ContextMenu("Create Panel Settings")]
    void CreatePanelSettings()
    {
#if UNITY_EDITOR
        // Ensure UI directory exists
        if (!AssetDatabase.IsValidFolder("Assets/UI"))
        {
            AssetDatabase.CreateFolder("Assets", "UI");
        }

        // Create Panel Settings asset
        var panelSettings = ScriptableObject.CreateInstance<PanelSettings>();

        // Set default values
        panelSettings.themeStyleSheet = null; // You can assign a theme if you have one
        panelSettings.targetTexture = null; // Will render to screen
        panelSettings.scaleMode = PanelScaleMode.ConstantPixelSize;
        panelSettings.scale = 1.0f;
        panelSettings.referenceResolution = new Vector2Int(1920, 1080);
        panelSettings.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
        panelSettings.match = 0.5f;
        panelSettings.sortingOrder = 10; // Set higher than main UI (which has sortingOrder 0)

        // Save the asset
        string panelSettingsPath = "Assets/UI/PanelSettings.asset";
        AssetDatabase.CreateAsset(panelSettings, panelSettingsPath);
        AssetDatabase.SaveAssets();

        Debug.Log($"Created Panel Settings at {panelSettingsPath}");

        // Assign to existing shop manager
        var shopManager = FindFirstObjectByType<SimpleShopManager>();
        if (shopManager != null)
        {
            var uiDocument = shopManager.GetComponent<UIDocument>();
            if (uiDocument != null)
            {
                uiDocument.panelSettings = panelSettings;
                Debug.Log("Assigned Panel Settings to ShopManager UIDocument!");
            }
        }
#else
        Debug.LogError("Panel Settings can only be created in the Editor!");
#endif
    }
    [ContextMenu("Test Shop UI Visibility")]
    void TestShopUIVisibility()
    {
        var shopManager = FindFirstObjectByType<SimpleShopManager>();
        if (shopManager == null)
        {
            Debug.LogError("No ShopManager found in scene!");
            return;
        }

        var uiDocument = shopManager.GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            Debug.LogError("ShopManager has no UIDocument!");
            return;
        }

        Debug.Log("=== Shop UI Visibility Test ===");
        Debug.Log($"UIDocument sortingOrder: {uiDocument.sortingOrder}");

        if (uiDocument.panelSettings != null)
        {
            Debug.Log($"Panel Settings sortingOrder: {uiDocument.panelSettings.sortingOrder}");
        }
        else
        {
            Debug.LogWarning("No Panel Settings assigned!");
        }

        // Compare with main UI
        var allUIDocuments = FindObjectsByType<UIDocument>(FindObjectsSortMode.None);
        Debug.Log("All UIDocuments in scene:");
        foreach (var doc in allUIDocuments)
        {
            var panelSort = doc.panelSettings?.sortingOrder ?? -999;
            Debug.Log($"  '{doc.gameObject.name}' - UIDoc sortOrder: {doc.sortingOrder}, Panel sortOrder: {panelSort}");
        }

        // Try to open the shop
        var mainTeamScript = FindFirstObjectByType<MainTeamSelectScript>();
        if (mainTeamScript != null)
        {
            // Create a dummy character for testing
            var dummyCharacter = new TeamCharacter();
            dummyCharacter.name = "Test Character";
            shopManager.OpenShop(dummyCharacter);
            Debug.Log("Shop opened for testing - check if it's visible above other UI!");
        }
        else
        {
            Debug.LogWarning("No MainTeamSelectScript found - cannot test shop opening");
        }
    }

    [ContextMenu("Fix Panel Settings Sort Order")]
    void FixPanelSettingsSortOrder()
    {
#if UNITY_EDITOR
        // Check if Panel Settings already exists
        string panelSettingsPath = "Assets/UI/PanelSettings.asset";
        var existingPanelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>(panelSettingsPath);

        if (existingPanelSettings != null)
        {
            existingPanelSettings.sortingOrder = 10; // Set higher than main UI (which has sortingOrder 0)
            EditorUtility.SetDirty(existingPanelSettings);
            AssetDatabase.SaveAssets();
            Debug.Log($"Updated Panel Settings sortingOrder to 10 for UI layering!");
        }
        else
        {
            Debug.LogWarning("Panel Settings not found. Run 'Create Panel Settings' first.");
        }

        // Also update any UIDocument that might be using this Panel Settings
        var shopManager = FindFirstObjectByType<SimpleShopManager>();
        if (shopManager != null)
        {
            var uiDocument = shopManager.GetComponent<UIDocument>();
            if (uiDocument != null && uiDocument.panelSettings != null)
            {
                uiDocument.panelSettings.sortingOrder = 10;
                EditorUtility.SetDirty(uiDocument.panelSettings);
                Debug.Log("Updated UIDocument Panel Settings sortingOrder!");
            }
        }
#else
        Debug.LogError("Panel Settings can only be modified in the Editor!");
#endif
    }
    [ContextMenu("Assign Shop UI Asset")]
    void AssignShopUIAsset()
    {
        var shopManager = FindFirstObjectByType<SimpleShopManager>();
        if (shopManager == null)
        {
            Debug.LogError("No ShopManager found in scene. Create one first.");
            return;
        }

        var uiDocument = shopManager.GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            Debug.LogError("ShopManager doesn't have a UIDocument component!");
            return;
        }

        if (shopUIAsset != null)
        {
            uiDocument.visualTreeAsset = shopUIAsset;
            Debug.Log("Successfully assigned ShopUI.uxml to UIDocument!");
        }
        else
        {
            Debug.LogError("No Shop UI Asset assigned! Please drag ShopUI.uxml to the Shop UI Asset field in the inspector.");
        }
    }

    void Start()
    {
        if (createShopGameObject)
        {
            CreateShopGameObject();
            createShopGameObject = false;
        }

        // Always ensure shop system is properly set up
        EnsureShopSystemSetup();
    }

    void EnsureShopSystemSetup()
    {
        var shopManager = FindFirstObjectByType<SimpleShopManager>();
        if (shopManager == null)
        {
            Debug.Log("No ShopManager found, creating one...");
            CreateShopGameObject();
            shopManager = FindFirstObjectByType<SimpleShopManager>();
        }

        if (shopManager != null)
        {
            var uiDocument = shopManager.GetComponent<UIDocument>();
            if (uiDocument != null)
            {
                // Check if Panel Settings is assigned
                if (uiDocument.panelSettings == null)
                {
                    Debug.Log("No Panel Settings assigned to ShopManager, creating one...");
                    CreatePanelSettings();
                }

                // Check if Visual Tree Asset is assigned
                if (uiDocument.visualTreeAsset == null)
                {
                    Debug.Log("No Visual Tree Asset assigned to ShopManager, assigning ShopUI.uxml...");
                    AssignShopUIAsset();
                }
            }
        }
    }

    [ContextMenu("Create Shop GameObject")]
    void CreateShopGameObject()
    {
        // Check if shop manager already exists
        var existingShop = FindFirstObjectByType<SimpleShopManager>();
        if (existingShop != null)
        {
            Debug.LogWarning("ShopManager already exists in scene!");
            return;
        }

        // Create shop GameObject
        GameObject shopGO = new GameObject("ShopManager");

        // Add UIDocument component FIRST (before SimpleShopManager)
        var uiDocument = shopGO.AddComponent<UIDocument>();

        // Add SimpleShopManager component AFTER UIDocument
        var shopManager = shopGO.AddComponent<SimpleShopManager>();

        Debug.Log("Created ShopManager GameObject. Now looking for ShopUI.uxml...");

        // Try to find and assign the UXML file - try multiple potential paths
        VisualTreeAsset uiAsset = null;

#if UNITY_EDITOR
        // Try to load from Assets folder directly (Editor only)
        uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/TeamSelectOverview/ShopUI.uxml");
        if (uiAsset != null)
        {
            Debug.Log("Found ShopUI.uxml in Assets/UI/TeamSelectOverview/");
            uiDocument.visualTreeAsset = uiAsset;

            // Try to find and assign Panel Settings
            var panelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>("Assets/UI/PanelSettings.asset");
            if (panelSettings == null)
            {
                // Try common locations for Panel Settings
                var panelSettingsGuids = AssetDatabase.FindAssets("t:PanelSettings");
                if (panelSettingsGuids.Length > 0)
                {
                    var panelSettingsPath = AssetDatabase.GUIDToAssetPath(panelSettingsGuids[0]);
                    panelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>(panelSettingsPath);
                    Debug.Log($"Found Panel Settings at: {panelSettingsPath}");
                }
                else
                {
                    // No Panel Settings found, create one
                    Debug.Log("No Panel Settings found, creating one...");
                    CreatePanelSettings();
                    panelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>("Assets/UI/PanelSettings.asset");
                }
            }

            if (panelSettings != null)
            {
                uiDocument.panelSettings = panelSettings;
                // Ensure the UIDocument also has a high sortingOrder for proper layering
                uiDocument.sortingOrder = 10;
                Debug.Log("Successfully assigned Panel Settings to UIDocument with sortingOrder 10!");
            }
            else
            {
                Debug.LogError("Failed to create or find Panel Settings!");
            }

            Debug.Log("Successfully assigned ShopUI.uxml to UIDocument!");
        }
        else
        {
            // Try Resources folder
            uiAsset = Resources.Load<VisualTreeAsset>("UI/TeamSelectOverview/ShopUI");
            if (uiAsset != null)
            {
                Debug.Log("Found ShopUI.uxml in Resources folder");
                uiDocument.visualTreeAsset = uiAsset;
                Debug.Log("Successfully assigned ShopUI.uxml to UIDocument!");
            }
            else
            {
                Debug.LogError("Could not find ShopUI.uxml! Please check that the file exists at Assets/UI/TeamSelectOverview/ShopUI.uxml");
                Debug.LogError("Manual assignment required: Select the ShopManager GameObject and assign ShopUI.uxml to the UIDocument component.");
            }
        }
#else
        // In build, try Resources folder
        uiAsset = Resources.Load<VisualTreeAsset>("UI/TeamSelectOverview/ShopUI");
        if (uiAsset != null)
        {
            uiDocument.visualTreeAsset = uiAsset;
            Debug.Log("Successfully assigned ShopUI.uxml to UIDocument!");
        }
        else
        {
            Debug.LogError("Could not find ShopUI.uxml in Resources folder!");
        }
#endif

        Debug.Log("The shop is now ready to use with the inventory system!");

        // Select the created GameObject in the hierarchy for easy inspection
#if UNITY_EDITOR
        UnityEditor.Selection.activeGameObject = shopGO;
#endif
    }
    [ContextMenu("Test Shop System")]
    void TestShopSystem()
    {
        var shopManager = FindFirstObjectByType<SimpleShopManager>();
        if (shopManager == null)
        {
            Debug.LogError("No ShopManager found in scene. Please create one first using 'Create Shop GameObject'.");
            return;
        }

        Debug.Log("Testing Shop System...");

        // Check if UIDocument is assigned
        var uiDocument = shopManager.GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            Debug.LogError("ShopManager doesn't have a UIDocument component!");
            return;
        }

        // Check if UXML is assigned
        if (uiDocument.visualTreeAsset == null)
        {
            Debug.LogError("UIDocument doesn't have a Visual Tree Asset assigned! Please assign ShopUI.uxml manually or use 'Assign Shop UI Asset' context menu.");
            return;
        }

        Debug.Log($"UIDocument found with asset: {uiDocument.visualTreeAsset.name}");

        // Check if UI elements can be found
        var root = uiDocument.rootVisualElement;
        var shopContainer = root.Q<VisualElement>("ShopContainer");
        Debug.Log($"ShopContainer found in root: {shopContainer != null}");

        if (shopContainer == null)
        {
            Debug.LogError("ShopContainer not found! This means the UXML structure might be wrong or not loaded properly.");
            Debug.Log("Checking root element children...");
            Debug.Log($"Root element has {root.childCount} children");
            for (int i = 0; i < root.childCount; i++)
            {
                var child = root.ElementAt(i);
                Debug.Log($"Child {i}: {child.name} (type: {child.GetType().Name})");
            }
            return;
        }

        // Test opening the shop
        var testCharacter = new TeamCharacter("Test Hero", true);
        testCharacter.gold = 100; // Give some starting money

        Debug.Log("Opening shop for test character...");
        shopManager.OpenShop(testCharacter);

        // Check if shop is actually visible
        Debug.Log($"Shop container display style: {shopContainer.style.display}");
        Debug.Log($"Shop container resolved style display: {shopContainer.resolvedStyle.display}");
        Debug.Log($"Shop container world bound: {shopContainer.worldBound}");
        Debug.Log($"Shop container local bound: {shopContainer.localBound}");

        Debug.Log("Shop test completed! If you don't see the shop window, check that:");
        Debug.Log("1. Panel Settings is assigned to the UIDocument");
        Debug.Log("2. No other UI is covering the shop");
        Debug.Log("3. The shop might be outside the camera view");
    }

    [ContextMenu("Debug Shop Setup")]
    void DebugShopSetup()
    {
        Debug.Log("=== SHOP SETUP DEBUG ===");

        var shopManager = FindFirstObjectByType<SimpleShopManager>();
        Debug.Log($"ShopManager found: {shopManager != null}");

        if (shopManager != null)
        {
            var uiDocument = shopManager.GetComponent<UIDocument>();
            Debug.Log($"UIDocument found: {uiDocument != null}");

            if (uiDocument != null)
            {
                Debug.Log($"Visual Tree Asset assigned: {uiDocument.visualTreeAsset != null}");
                if (uiDocument.visualTreeAsset != null)
                {
                    Debug.Log($"Asset name: {uiDocument.visualTreeAsset.name}");
                }
            }
        }

        // Check if UXML file exists
#if UNITY_EDITOR
        var uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/TeamSelectOverview/ShopUI.uxml");
        Debug.Log($"ShopUI.uxml exists at expected path: {uiAsset != null}");
#endif

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