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

/// <summary>
/// Helper component to ensure the shop system is properly configured
/// Add this to any GameObject in the MainTeamSelectScene to automatically setup the shop
/// </summary>
public class ShopSystemSetup : MonoBehaviour
{
    [Header("Shop Configuration")]
    [Tooltip("The name of the shop")]
    public string shopName = "General Store";

    [Header("Auto-Setup Options")]
    [Tooltip("Automatically create an ItemShopManager if none exists")]
    public bool autoCreateShopManager = true;

    [Tooltip("Automatically load and verify items on start")]
    public bool autoVerifyItems = true;

    [Header("Debug Options")]
    [Tooltip("Show debug information in console")]
    public bool enableDebugLogging = true;

    void Start()
    {
        if (autoCreateShopManager)
        {
            SetupShopManager();
        }

        if (autoVerifyItems)
        {
            VerifyItems();
        }
    }

    void SetupShopManager()
    {
        // Check if ItemShopManager already exists
        ItemShopManager existingManager = FindFirstObjectByType<ItemShopManager>();

        if (existingManager != null)
        {
            if (enableDebugLogging)
                Debug.Log($"ItemShopManager already exists on '{existingManager.gameObject.name}'");
            return;
        }

        // Check for old SimpleShopManager and warn
        SimpleShopManager oldManager = FindFirstObjectByType<SimpleShopManager>();
        if (oldManager != null)
        {
            Debug.LogWarning($"Found SimpleShopManager on '{oldManager.gameObject.name}'. Please use the migration tool: RPG > Migrate Shop System");
            return;
        }

        // Find a suitable GameObject to add the shop to
        GameObject shopObject = null;

        // Look for existing shop-related GameObjects
        GameObject[] allObjects = FindObjectsByType<GameObject>(FindObjectsSortMode.None);
        foreach (GameObject obj in allObjects)
        {
            if (obj.name.ToLower().Contains("shop"))
            {
                shopObject = obj;
                break;
            }
        }

        // If no shop object found, use this GameObject
        if (shopObject == null)
        {
            shopObject = this.gameObject;
        }

        // Add ItemShopManager if it doesn't exist
        ItemShopManager shopManager = shopObject.GetComponent<ItemShopManager>();
        if (shopManager == null)
        {
            shopManager = shopObject.AddComponent<ItemShopManager>();
            shopManager.shopName = shopName;

            if (enableDebugLogging)
                Debug.Log($"Created ItemShopManager on '{shopObject.name}'");
        }

        // Ensure UIDocument exists
        UIDocument uiDocument = shopObject.GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            uiDocument = shopObject.AddComponent<UIDocument>();

            if (enableDebugLogging)
                Debug.Log($"Added UIDocument component to '{shopObject.name}'");
        }

        // Try to find and assign ShopUI.uxml
        if (uiDocument.visualTreeAsset == null)
        {
            var shopUI = Resources.Load<VisualTreeAsset>("UI/ShopUI");
            if (shopUI == null)
            {
                // Try alternative paths
                string[] possiblePaths = {
                    "ShopUI",
                    "UI/ShopUI",
                    "TeamSelectOverview/ShopUI"
                };

                foreach (string path in possiblePaths)
                {
                    shopUI = Resources.Load<VisualTreeAsset>(path);
                    if (shopUI != null)
                    {
                        if (enableDebugLogging)
                            Debug.Log($"Found ShopUI at path: {path}");
                        break;
                    }
                }
            }

            if (shopUI != null)
            {
                uiDocument.visualTreeAsset = shopUI;
                if (enableDebugLogging)
                    Debug.Log("Assigned ShopUI.uxml to UIDocument");
            }
            else
            {
                Debug.LogWarning("Could not find ShopUI.uxml. Please assign it manually to the UIDocument component.");
            }
        }

        // Set up panel settings with proper sorting order
        SetupPanelSettings(uiDocument);
    }

    void SetupPanelSettings(UIDocument uiDoc)
    {
        // First try to find and reuse existing panel settings from other UI
        var existingUI = GameObject.Find("TravelUI")?.GetComponent<UIDocument>();
        if (existingUI?.panelSettings != null)
        {
            uiDoc.panelSettings = existingUI.panelSettings;
            if (enableDebugLogging)
                Debug.Log("✓ Panel Settings assigned from TravelUI");
        }
        else
        {
            // Try to find from MainTeamSelectScript or other UI components
            var mainTeamSelect = FindFirstObjectByType<MainTeamSelectScript>();
            if (mainTeamSelect != null)
            {
                var mainUIDoc = mainTeamSelect.GetComponent<UIDocument>();
                if (mainUIDoc?.panelSettings != null)
                {
                    uiDoc.panelSettings = mainUIDoc.panelSettings;
                    if (enableDebugLogging)
                        Debug.Log("✓ Panel Settings assigned from MainTeamSelectScript");
                }
            }
        }

        // If still no panel settings, try to find any PanelSettings asset
        if (uiDoc.panelSettings == null)
        {
#if UNITY_EDITOR
            var panelSettingsGuids = UnityEditor.AssetDatabase.FindAssets("t:PanelSettings");
            if (panelSettingsGuids.Length > 0)
            {
                var path = UnityEditor.AssetDatabase.GUIDToAssetPath(panelSettingsGuids[0]);
                var settings = UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.PanelSettings>(path);
                uiDoc.panelSettings = settings;
                if (enableDebugLogging)
                    Debug.Log($"✓ Panel Settings auto-assigned: {settings.name}");
            }
#endif
        }

        // Set proper sorting order (> 2 as requested)
        uiDoc.sortingOrder = 5; // Higher than 2 to ensure shop displays on top

        if (uiDoc.panelSettings != null)
        {
            // Make sure panel settings also have a high sorting order
            uiDoc.panelSettings.sortingOrder = 5;
            if (enableDebugLogging)
                Debug.Log($"✓ Shop UI sorting order set to {uiDoc.sortingOrder}");
        }
        else
        {
            Debug.LogWarning("⚠ Could not assign Panel Settings. You may need to assign it manually.");
        }
    }

    void VerifyItems()
    {
        // Load all items from Resources
        Item[] items = Resources.LoadAll<Item>("Items");

        if (items.Length == 0)
        {
            if (enableDebugLogging)
            {
                Debug.LogWarning("No Item ScriptableObjects found in Resources/Items folder.");
                Debug.Log("To create sample items, use: RPG > Create Sample Items");
                Debug.Log("Or create your own items using: Create > RPG > Items");
            }
        }
        else
        {
            if (enableDebugLogging)
            {
                Debug.Log($"Found {items.Length} items for the shop:");
                foreach (Item item in items)
                {
                    Debug.Log($"  - {item.itemName} ({item.itemType}) - {item.GetCostString()}");
                }
            }
        }

        // Check for items in the direct Resources folder as well
        Item[] directItems = Resources.LoadAll<Item>("");
        int additionalItems = 0;
        foreach (Item item in directItems)
        {
            bool alreadyCounted = false;
            foreach (Item folderItem in items)
            {
                if (item == folderItem)
                {
                    alreadyCounted = true;
                    break;
                }
            }

            if (!alreadyCounted)
            {
                additionalItems++;
                if (enableDebugLogging)
                    Debug.Log($"  - {item.itemName} (found in Resources root)");
            }
        }

        if (additionalItems > 0 && enableDebugLogging)
        {
            Debug.Log($"Also found {additionalItems} additional items in Resources root folder");
        }
    }

    [ContextMenu("Force Setup Shop")]
    public void ForceSetupShop()
    {
        SetupShopManager();
    }

    [ContextMenu("Verify Items")]
    public void ForceVerifyItems()
    {
        VerifyItems();
    }

    [ContextMenu("Full Shop Verification")]
    public void FullVerification()
    {
        Debug.Log("=== Shop System Full Verification ===");

        SetupShopManager();
        VerifyItems();

        // Additional checks
        ItemShopManager shopManager = FindFirstObjectByType<ItemShopManager>();
        if (shopManager != null)
        {
            UIDocument uiDoc = shopManager.GetComponent<UIDocument>();
            if (uiDoc != null && uiDoc.visualTreeAsset != null)
            {
                Debug.Log("✓ Shop system appears to be fully configured");
            }
            else
            {
                Debug.LogWarning("⚠ Shop system needs UI configuration");
            }
        }
        else
        {
            Debug.LogError("✗ No ItemShopManager found");
        }

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

    // Cleanup method to prevent interference
    void OnValidate()
    {
        // Ensure this component doesn't interfere with the actual shop
        if (string.IsNullOrEmpty(shopName))
        {
            shopName = "General Store";
        }
    }
}
