using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;

public class ShopSystemMigrator
{
    [MenuItem("RPG/Migrate Shop System")]
    public static void MigrateShopSystem()
    {
        // Load the MainTeamSelectScene
        Scene scene = EditorSceneManager.OpenScene("Assets/Scenes/MainTeamSelectScene.unity");

        if (!scene.IsValid())
        {
            Debug.LogError("Could not load MainTeamSelectScene.unity");
            return;
        }

        bool changesMade = false;

        // Find all SimpleShopManager components in the scene
        SimpleShopManager[] oldShopManagers = Object.FindObjectsByType<SimpleShopManager>(FindObjectsSortMode.None);

        foreach (SimpleShopManager oldManager in oldShopManagers)
        {
            GameObject shopObject = oldManager.gameObject;

            // Store the old settings
            string shopName = oldManager.shopName;
            var uiDocument = shopObject.GetComponent<UIDocument>();

            Debug.Log($"Converting SimpleShopManager on '{shopObject.name}' to ItemShopManager");

            // Remove the old component
            Object.DestroyImmediate(oldManager);

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

            changesMade = true;
        }

        if (changesMade)
        {
            // Mark the scene as dirty so Unity knows it needs to be saved
            EditorSceneManager.MarkSceneDirty(scene);

            // Save the scene
            EditorSceneManager.SaveScene(scene);

            Debug.Log($"Successfully migrated {oldShopManagers.Length} SimpleShopManager(s) to ItemShopManager in MainTeamSelectScene");
            Debug.Log("The scene has been saved with the changes.");
        }
        else
        {
            Debug.Log("No SimpleShopManager components found in MainTeamSelectScene to migrate.");
        }
    }

    [MenuItem("RPG/Setup New Shop System")]
    public static void SetupNewShopSystem()
    {
        // Load the MainTeamSelectScene
        Scene scene = EditorSceneManager.OpenScene("Assets/Scenes/MainTeamSelectScene.unity");

        if (!scene.IsValid())
        {
            Debug.LogError("Could not load MainTeamSelectScene.unity");
            return;
        }

        // Check if there's already an ItemShopManager
        ItemShopManager[] existingManagers = Object.FindObjectsByType<ItemShopManager>(FindObjectsSortMode.None);

        if (existingManagers.Length > 0)
        {
            Debug.Log($"Found {existingManagers.Length} existing ItemShopManager(s) in the scene.");
            return;
        }

        // Find objects that might need a shop manager (look for UIDocument with shop-related names)
        UIDocument[] uiDocuments = Object.FindObjectsByType<UIDocument>(FindObjectsSortMode.None);

        GameObject shopObject = null;

        // Look for a GameObject that might be the shop
        foreach (UIDocument uiDoc in uiDocuments)
        {
            if (uiDoc.gameObject.name.ToLower().Contains("shop"))
            {
                shopObject = uiDoc.gameObject;
                break;
            }
        }

        // If no shop object found, create a new one
        if (shopObject == null)
        {
            shopObject = new GameObject("ShopManager");

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

            // Try to find ShopUI.uxml
            string[] guids = AssetDatabase.FindAssets("ShopUI t:VisualTreeAsset");
            if (guids.Length > 0)
            {
                string path = AssetDatabase.GUIDToAssetPath(guids[0]);
                var visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(path);
                uiDocument.visualTreeAsset = visualTreeAsset;
                Debug.Log($"Assigned ShopUI.uxml to UIDocument: {path}");
            }
            else
            {
                Debug.LogWarning("ShopUI.uxml not found. You'll need to assign it manually to the UIDocument component.");
            }
        }

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

        // Mark the scene as dirty and save
        EditorSceneManager.MarkSceneDirty(scene);
        EditorSceneManager.SaveScene(scene);

        Debug.Log($"Created ItemShopManager on '{shopObject.name}' in MainTeamSelectScene");
        Debug.Log("Don't forget to:");
        Debug.Log("1. Assign ShopUI.uxml to the UIDocument component if not already done");
        Debug.Log("2. Run 'RPG > Create Sample Items' to create some items to sell");
        Debug.Log("3. Create your own Item ScriptableObjects using the Create menu (RPG > Items)");
    }

    [MenuItem("RPG/Verify Shop Setup")]
    public static void VerifyShopSetup()
    {
        // Load the MainTeamSelectScene
        Scene scene = EditorSceneManager.OpenScene("Assets/Scenes/MainTeamSelectScene.unity");

        if (!scene.IsValid())
        {
            Debug.LogError("Could not load MainTeamSelectScene.unity");
            return;
        }

        Debug.Log("=== Shop System Verification ===");

        // Check for ItemShopManager
        ItemShopManager[] shopManagers = Object.FindObjectsByType<ItemShopManager>(FindObjectsSortMode.None);
        Debug.Log($"ItemShopManager components found: {shopManagers.Length}");

        // Check for remaining SimpleShopManager (should be 0)
        SimpleShopManager[] oldManagers = Object.FindObjectsByType<SimpleShopManager>(FindObjectsSortMode.None);
        if (oldManagers.Length > 0)
        {
            Debug.LogWarning($"Found {oldManagers.Length} SimpleShopManager components that still need migration!");
        }

        // Check for items in Resources
        Item[] items = Resources.LoadAll<Item>("Items");
        Debug.Log($"Item ScriptableObjects found in Resources/Items: {items.Length}");

        if (items.Length == 0)
        {
            Debug.LogWarning("No Item ScriptableObjects found! Run 'RPG > Create Sample Items' to create some.");
        }
        else
        {
            Debug.Log("Available items:");
            foreach (Item item in items)
            {
                Debug.Log($"  - {item.itemName} ({item.itemType})");
            }
        }

        // Check UIDocument setup
        foreach (ItemShopManager manager in shopManagers)
        {
            UIDocument uiDoc = manager.GetComponent<UIDocument>();
            if (uiDoc == null)
            {
                Debug.LogWarning($"ItemShopManager on '{manager.gameObject.name}' is missing UIDocument component!");
            }
            else if (uiDoc.visualTreeAsset == null)
            {
                Debug.LogWarning($"UIDocument on '{manager.gameObject.name}' is missing Visual Tree Asset (ShopUI.uxml)!");
            }
            else
            {
                Debug.Log($"✓ ItemShopManager on '{manager.gameObject.name}' appears to be properly configured");
            }
        }

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