using UnityEngine;
using UnityEditor;
using System.IO;

/// <summary>
/// Editor utility to help migrate EnemyCharacterData assets to use WeaponItem references
/// instead of WeaponType enums
/// </summary>
public class EnemyWeaponMigrationTool : EditorWindow
{
    private bool showInstructions = true;
    private Vector2 scrollPosition;

    [MenuItem("RPG Tools/Enemy Weapon Migration Tool")]
    static void Init()
    {
        EnemyWeaponMigrationTool window = (EnemyWeaponMigrationTool)EditorWindow.GetWindow(typeof(EnemyWeaponMigrationTool));
        window.titleContent = new GUIContent("Enemy Weapon Migration");
        window.Show();
    }

    void OnGUI()
    {
        GUILayout.Label("Enemy Weapon Migration Tool", EditorStyles.boldLabel);
        GUILayout.Space(10);

        showInstructions = EditorGUILayout.Foldout(showInstructions, "Instructions");
        if (showInstructions)
        {
            EditorGUILayout.HelpBox(
                "This tool helps migrate existing EnemyCharacterData assets to use WeaponItem references instead of WeaponType enums.\n\n" +
                "BEFORE MIGRATION:\n" +
                "1. Create WeaponItem assets for your desired weapons\n" +
                "2. Configure weapon stats, prefabs, and class names\n" +
                "3. Save the WeaponItem assets in your project\n\n" +
                "MIGRATION PROCESS:\n" +
                "1. Click 'Find Enemy Assets' to scan for EnemyCharacterData assets\n" +
                "2. Review the list of enemies found\n" +
                "3. For each enemy, drag the appropriate WeaponItem into the field\n" +
                "4. Click 'Apply Changes' to update the assets\n\n" +
                "NOTE: This migration is manual to ensure you assign the correct weapons.",
                MessageType.Info);
        }

        GUILayout.Space(10);

        if (GUILayout.Button("Create Sample WeaponItem Assets"))
        {
            CreateSampleWeaponItems();
        }

        GUILayout.Space(10);

        if (GUILayout.Button("Find EnemyCharacterData Assets"))
        {
            FindEnemyAssets();
        }

        GUILayout.Space(10);

        // Display found assets
        if (enemyAssets != null && enemyAssets.Length > 0)
        {
            GUILayout.Label($"Found {enemyAssets.Length} Enemy Assets:", EditorStyles.boldLabel);

            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

            for (int i = 0; i < enemyAssets.Length; i++)
            {
                var enemy = enemyAssets[i];
                if (enemy != null)
                {
                    EditorGUILayout.BeginHorizontal("box");

                    EditorGUILayout.LabelField(enemy.enemyName, GUILayout.Width(120));
                    EditorGUILayout.LabelField($"Health: {enemy.maxHealth}", GUILayout.Width(80));

                    // Show current weapon assignment
                    enemy.preferredWeapon = (WeaponItem)EditorGUILayout.ObjectField(
                        "Weapon:",
                        enemy.preferredWeapon,
                        typeof(WeaponItem),
                        false,
                        GUILayout.Width(200));

                    if (GUILayout.Button("Select Asset", GUILayout.Width(100)))
                    {
                        Selection.activeObject = enemy;
                        EditorGUIUtility.PingObject(enemy);
                    }

                    EditorGUILayout.EndHorizontal();
                }
            }

            EditorGUILayout.EndScrollView();

            GUILayout.Space(10);

            if (GUILayout.Button("Save All Changes"))
            {
                SaveAllChanges();
            }
        }
    }

    private EnemyCharacterData[] enemyAssets;

    void FindEnemyAssets()
    {
        string[] guids = AssetDatabase.FindAssets("t:EnemyCharacterData");
        enemyAssets = new EnemyCharacterData[guids.Length];

        for (int i = 0; i < guids.Length; i++)
        {
            string path = AssetDatabase.GUIDToAssetPath(guids[i]);
            enemyAssets[i] = AssetDatabase.LoadAssetAtPath<EnemyCharacterData>(path);
        }

        Debug.Log($"Found {enemyAssets.Length} EnemyCharacterData assets");
    }

    void CreateSampleWeaponItems()
    {
        // Create a folder for sample weapons if it doesn't exist
        string folderPath = "Assets/Resources/SampleWeapons";
        if (!AssetDatabase.IsValidFolder(folderPath))
        {
            AssetDatabase.CreateFolder("Assets/Resources", "SampleWeapons");
        }

        // Create sample sword
        var sword = ScriptableObject.CreateInstance<WeaponItem>();
        sword.itemName = "Enemy Sword";
        sword.description = "A basic sword for enemy characters";
        sword.minDamage = 2;
        sword.maxDamage = 6;
        sword.range = 2;
        sword.weaponModifier = 0;
        sword.attackSpeed = 1.0f;
        sword.weaponType = WeaponType.Sword;
        sword.weaponClassName = "SimpleSword";
        sword.goldCost = 10;

        AssetDatabase.CreateAsset(sword, $"{folderPath}/EnemySword.asset");

        // Create sample bow
        var bow = ScriptableObject.CreateInstance<WeaponItem>();
        bow.itemName = "Enemy Bow";
        bow.description = "A basic bow for enemy archers";
        bow.minDamage = 1;
        bow.maxDamage = 6;
        bow.range = 100;
        bow.weaponModifier = 0;
        bow.attackSpeed = 2.0f;
        bow.weaponType = WeaponType.Bow;
        bow.weaponClassName = "SimpleBow";
        bow.goldCost = 15;

        AssetDatabase.CreateAsset(bow, $"{folderPath}/EnemyBow.asset");

        // Create sample dagger
        var dagger = ScriptableObject.CreateInstance<WeaponItem>();
        dagger.itemName = "Enemy Dagger";
        dagger.description = "A fast dagger for quick enemies";
        dagger.minDamage = 1;
        dagger.maxDamage = 4;
        dagger.range = 1;
        dagger.weaponModifier = 1;
        dagger.attackSpeed = 0.8f;
        dagger.weaponType = WeaponType.Dagger;
        dagger.weaponClassName = "SimpleSword"; // Using sword class as base
        dagger.goldCost = 8;

        AssetDatabase.CreateAsset(dagger, $"{folderPath}/EnemyDagger.asset");

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        Debug.Log("Created sample WeaponItem assets in " + folderPath);
        EditorUtility.DisplayDialog("Sample Weapons Created",
            $"Created sample weapon assets:\n• Enemy Sword\n• Enemy Bow\n• Enemy Dagger\n\nLocation: {folderPath}",
            "OK");
    }

    void SaveAllChanges()
    {
        if (enemyAssets == null) return;

        int updatedCount = 0;

        foreach (var enemy in enemyAssets)
        {
            if (enemy != null)
            {
                EditorUtility.SetDirty(enemy);
                updatedCount++;
            }
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        Debug.Log($"Updated {updatedCount} enemy assets");
        EditorUtility.DisplayDialog("Migration Complete",
            $"Successfully updated {updatedCount} enemy assets.\n\nAll changes have been saved.",
            "OK");
    }
}
