#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;

/// <summary>
/// Editor utility to clear _GrayscaleTex from materials.
/// Useful for cleaning up material previews after runtime testing.
/// </summary>
public class ClearGrayscaleTextures : EditorWindow
{
    private bool showWarning = true;

    [MenuItem("Tools/MesshingAround/Clear GrayscaleTex from Materials")]
    static void ShowWindow()
    {
        GetWindow<ClearGrayscaleTextures>("Clear GrayscaleTex");
    }

    void OnGUI()
    {
        EditorGUILayout.Space(10);

        EditorGUILayout.LabelField("Clear GrayscaleTex from Materials", EditorStyles.boldLabel);
        EditorGUILayout.Space(5);

        EditorGUILayout.HelpBox(
            "This tool clears the _GrayscaleTex property from all materials.\n\n" +
            "This is useful for cleaning up material previews in the Project window. " +
            "The grayscale texture will be re-applied automatically at runtime by PotionTextureSetup.",
            MessageType.Info
        );

        EditorGUILayout.Space(10);

        // Warning box
        if (showWarning)
        {
            EditorGUILayout.HelpBox(
                "⚠️ IMPORTANT WARNINGS:\n\n" +
                "• Material Instances: If you have material instances in your scene (created via 'Prepare for Timeline'), " +
                "you may need to reset them after running this tool.\n\n" +
                "• White Materials: After clearing, materials in the scene may appear white or without the grayscale texture " +
                "until you enter Play mode or force a repaint (Play/Stop).\n\n" +
                "• This operation affects ALL materials in the project with _GrayscaleTex property.",
                MessageType.Warning
            );
        }

        EditorGUILayout.Space(10);

        showWarning = EditorGUILayout.ToggleLeft("Show warnings", showWarning);

        EditorGUILayout.Space(10);

        GUI.backgroundColor = new Color(0.8f, 0.4f, 0.4f);
        if (GUILayout.Button("Clear _GrayscaleTex from All Materials", GUILayout.Height(40)))
        {
            if (EditorUtility.DisplayDialog(
                "Clear GrayscaleTex",
                "Are you sure you want to clear _GrayscaleTex from all materials?\n\n" +
                "This will affect all materials in the project.\n" +
                "Material instances may need to be recreated.",
                "Yes, Clear",
                "Cancel"))
            {
                ClearAllGrayscaleTextures();
            }
        }
        GUI.backgroundColor = Color.white;

        EditorGUILayout.Space(10);

        EditorGUILayout.HelpBox(
            "💡 TIP: After running this tool:\n" +
            "1. Enter Play mode and Stop to refresh materials in the scene\n" +
            "2. If materials are still white, re-assign the material to the Renderer\n" +
            "3. If using Timeline, you may need to re-run 'Prepare for Timeline' on affected objects",
            MessageType.Info
        );
    }

    void ClearAllGrayscaleTextures()
    {
        string[] guids = AssetDatabase.FindAssets("t:Material");
        int clearedCount = 0;
        int totalChecked = 0;

        EditorUtility.DisplayProgressBar("Clearing GrayscaleTex", "Processing materials...", 0f);

        try
        {
            for (int i = 0; i < guids.Length; i++)
            {
                string path = AssetDatabase.GUIDToAssetPath(guids[i]);
                Material mat = AssetDatabase.LoadAssetAtPath<Material>(path);

                if (mat != null)
                {
                    totalChecked++;

                    if (mat.HasProperty("_GrayscaleTex"))
                    {
                        Texture currentTex = mat.GetTexture("_GrayscaleTex");

                        if (currentTex != null)
                        {
                            mat.SetTexture("_GrayscaleTex", null);
                            EditorUtility.SetDirty(mat);
                            clearedCount++;
                            Debug.Log($"✓ Cleared _GrayscaleTex from: {mat.name} (was: {currentTex.name})");
                        }
                    }
                }

                float progress = (float)i / guids.Length;
                EditorUtility.DisplayProgressBar("Clearing GrayscaleTex", $"Processing {i + 1}/{guids.Length}", progress);
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        finally
        {
            EditorUtility.ClearProgressBar();
        }

        // Show results dialog
        string message = $"Operation completed!\n\n" +
                        $"• Materials checked: {totalChecked}\n" +
                        $"• Materials cleared: {clearedCount}\n\n" +
                        $"Remember to:\n" +
                        $"1. Enter Play mode to refresh scene materials\n" +
                        $"2. Re-run 'Prepare for Timeline' if needed";

        EditorUtility.DisplayDialog("Clear GrayscaleTex - Complete", message, "OK");

        Debug.Log($"===== CLEAR GRAYSCALETEX COMPLETE =====");
        Debug.Log($"✅ Cleared _GrayscaleTex from {clearedCount}/{totalChecked} material(s)");
    }
}
#endif