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

/// <summary>
/// Quick setup component to add to any GameObject in the scene to automatically configure the shop
/// Just add this component to any GameObject and it will set everything up for you
/// </summary>
public class QuickShopSetup : MonoBehaviour
{
    [Header("Quick Setup")]
    [Tooltip("Click this in play mode to automatically setup the shop")]
    public bool autoSetupOnStart = true;

    [Header("Setup Results")]
    [SerializeField] private bool shopSetupComplete = false;
    [SerializeField] private string statusMessage = "Not setup yet";

    /// <summary>
    /// Gets the current status message for debugging purposes
    /// </summary>
    public string GetStatusMessage() => statusMessage;

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

    [ContextMenu("Setup Shop Now")]
    public void SetupShop()
    {
        Debug.Log("=== Quick Shop Setup Starting ===");

        // Check if ItemShopManager already exists
        ItemShopManager existingShop = FindFirstObjectByType<ItemShopManager>();
        if (existingShop != null)
        {
            // Check if the UIDocument has the UXML assigned
            UIDocument uiDoc = existingShop.GetComponent<UIDocument>();
            if (uiDoc != null && uiDoc.visualTreeAsset == null)
            {
                Debug.Log("Found ItemShopManager but UIDocument needs UXML assignment...");
                AssignShopUIXML(uiDoc);
                statusMessage = "Fixed UXML assignment for existing shop";
                shopSetupComplete = true;
                return;
            }
            else if (uiDoc != null && uiDoc.visualTreeAsset != null)
            {
                statusMessage = "Shop already exists and is configured";
                shopSetupComplete = true;
                Debug.Log("✓ ItemShopManager already exists and is properly configured on: " + existingShop.gameObject.name);
                return;
            }
        }

        // Check for old SimpleShopManager
        SimpleShopManager oldShop = FindFirstObjectByType<SimpleShopManager>();
        if (oldShop != null)
        {
            Debug.Log("Found old SimpleShopManager, converting to ItemShopManager...");
            ConvertOldShop(oldShop);
            statusMessage = "Converted old shop to new system";
            shopSetupComplete = true;
            return;
        }

        // No shop exists, create new one
        Debug.Log("No shop found, creating new ItemShopManager...");
        CreateNewShop();
        statusMessage = "Created new shop system";
        shopSetupComplete = true;
    }

    void ConvertOldShop(SimpleShopManager oldShop)
    {
        GameObject shopObject = oldShop.gameObject;
        string shopName = oldShop.shopName;

        // Remove old component
        DestroyImmediate(oldShop);

        // Add new component
        ItemShopManager newShop = shopObject.AddComponent<ItemShopManager>();
        newShop.shopName = shopName;

        // Set up UIDocument with proper panel settings
        UIDocument uiDoc = shopObject.GetComponent<UIDocument>();
        if (uiDoc == null)
        {
            uiDoc = shopObject.AddComponent<UIDocument>();
        }

        // Assign ShopUI.uxml
        AssignShopUIXML(uiDoc);

        // Set up panel settings
        SetupPanelSettings(uiDoc);

        Debug.Log("✓ Converted SimpleShopManager to ItemShopManager on: " + shopObject.name);
    }

    void CreateNewShop()
    {
        // Create shop GameObject
        GameObject shopObject = new GameObject("ShopManager");

        // Add UIDocument
        UIDocument uiDoc = shopObject.AddComponent<UIDocument>();

        // Assign ShopUI.uxml
        AssignShopUIXML(uiDoc);

        // Assign Panel Settings and set proper sorting order
        SetupPanelSettings(uiDoc);

        // Add ItemShopManager
        ItemShopManager shopManager = shopObject.AddComponent<ItemShopManager>();
        shopManager.shopName = "General Store";

        Debug.Log("✓ Created new shop system on: " + shopObject.name);
    }
    void AssignShopUIXML(UIDocument uiDoc)
    {
        // Try multiple paths to find ShopUI.uxml
        string[] possiblePaths = {
            "UI/TeamSelectOverview/ShopUI",
            "TeamSelectOverview/ShopUI",
            "UI/ShopUI",
            "ShopUI"
        };

        VisualTreeAsset shopUI = null;
        string foundPath = "";

        foreach (string path in possiblePaths)
        {
            shopUI = Resources.Load<VisualTreeAsset>(path);
            if (shopUI != null)
            {
                foundPath = path;
                break;
            }
        }

        // If not found in Resources, try to load directly from Assets
        if (shopUI == null)
        {
#if UNITY_EDITOR
            string[] guids = UnityEditor.AssetDatabase.FindAssets("ShopUI t:VisualTreeAsset");
            if (guids.Length > 0)
            {
                string assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[0]);
                shopUI = UnityEditor.AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(assetPath);
                foundPath = assetPath;
                Debug.Log($"Found ShopUI.uxml at: {assetPath}");
            }
#endif
        }

        if (shopUI != null)
        {
            uiDoc.visualTreeAsset = shopUI;
            Debug.Log($"✓ Assigned ShopUI.uxml from {foundPath} to UIDocument");
        }
        else
        {
            Debug.LogError("❌ Could not find ShopUI.uxml! Please assign it manually in the UIDocument component.");
        }
    }

    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;
            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;
                    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;
                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;
            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.");
        }
    }

    [ContextMenu("Create Sample Items")]
    public void CreateSampleItems()
    {
        Debug.Log("=== Creating Sample Items ===");

        // Check if sample items already exist
        Item[] existingItems = Resources.LoadAll<Item>("Items");
        if (existingItems.Length > 0)
        {
            Debug.Log($"Found {existingItems.Length} existing items - no need to create samples");
            return;
        }

        // Create sample items programmatically
        CreateRuntimeItems();
        Debug.Log("✓ Created sample items");
    }

    void CreateRuntimeItems()
    {
        // Note: These are runtime items, not asset files
        // For permanent items, use the editor script: RPG > Create Sample Items

        var sword = ScriptableObject.CreateInstance<WeaponItem>();
        sword.itemName = "Iron Sword";
        sword.description = "A sturdy iron sword";
        sword.goldCost = 15;
        sword.minDamage = 2;
        sword.maxDamage = 8;
        sword.weaponType = WeaponType.Sword;

        var bow = ScriptableObject.CreateInstance<WeaponItem>();
        bow.itemName = "Hunting Bow";
        bow.description = "A reliable hunting bow";
        bow.goldCost = 12;
        bow.minDamage = 1;
        bow.maxDamage = 6;
        bow.range = 150;
        bow.weaponType = WeaponType.Bow;

        var armor = ScriptableObject.CreateInstance<ArmorItem>();
        armor.itemName = "Leather Armor";
        armor.description = "Basic leather protection";
        armor.goldCost = 10;
        armor.armorClass = 1;
        armor.armorType = ArmorType.Light;
        armor.armorSlot = ArmorSlot.Chest;

        var potion = ScriptableObject.CreateInstance<MiscellaneousItem>();
        potion.itemName = "Health Potion";
        potion.description = "Restores health";
        potion.goldCost = 5;
        potion.isConsumable = true;
        potion.healthDiceCount = 1;
        potion.healthDiceType = 6;
        potion.healthBonus = 1;

        Debug.Log("Created runtime items: Iron Sword, Hunting Bow, Leather Armor, Health Potion");
        Debug.Log("Note: These are temporary runtime items. For permanent items, use RPG > Create Sample Items menu");
    }

    [ContextMenu("Test Shop")]
    public void TestShop()
    {
        ItemShopManager shop = FindFirstObjectByType<ItemShopManager>();
        if (shop == null)
        {
            Debug.LogError("No ItemShopManager found! Run Setup Shop first.");
            return;
        }

        // Try to find a character to test with
        var teamSelectScript = FindFirstObjectByType<MainTeamSelectScript>();
        if (teamSelectScript != null)
        {
            Debug.Log("✓ Found MainTeamSelectScript - shop should work with character selection");
        }
        else
        {
            Debug.LogWarning("⚠ No MainTeamSelectScript found - shop might not have character context");
        }

        Debug.Log("Shop test complete - try clicking on character equipment slots to open shop");
    }

    void OnValidate()
    {
        if (Application.isPlaying && autoSetupOnStart && !shopSetupComplete)
        {
            SetupShop();
        }
    }
}
