// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

#if WPFMA_VRC_AVATARS
using VRC.SDK3.Avatars.Components;
using VRC.SDK3.Avatars.ScriptableObjects;
#endif

namespace WPFMA
{
    internal static class WPFMAToggleCreatorSection
    {
        private const string SectionTitle = "Toggle creator";
        private const string ExpandedPrefKey = "WPFMA.Tools.ToggleCreatorExpanded";

        private static Color AccentBlue => WPFMATheme.Shift(new Color(126f / 255f, 182f / 255f, 222f / 255f));
        private static Color ToolbarBackground => WPFMATheme.Shift(new Color(24f / 255f, 29f / 255f, 37f / 255f));
        private static Color ToolbarEdge => WPFMATheme.Shift(new Color(11f / 255f, 14f / 255f, 18f / 255f));
        private static Color FaintText => WPFMATheme.Shift(new Color(78f / 255f, 91f / 255f, 105f / 255f));
        private static readonly Color WarnAmber = new Color(239f / 255f, 159f / 255f, 39f / 255f);
        private static readonly Color OkGreen = new Color(93f / 255f, 202f / 255f, 165f / 255f);

#if WPFMA_VRC_AVATARS
        private static readonly WPFMAToggleCreator.Request Request = new WPFMAToggleCreator.Request();
        private static string status;
        private static bool statusIsError;
        private static List<string> notes = new List<string>();
        private static bool useSelection = true;
        private static bool showAdvanced;
        private static string newMenuName = string.Empty;
        private static UnityEditor.Animations.AnimatorController combinableFor;
        private static int combinableDirty = -1;
        private static int combinableCount;
#endif

        internal static void Draw(GUIStyle sectionStyle, GUIStyle titleStyle, GUIStyle pathStyle)
        {
            EditorGUILayout.Space(10f);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(sectionStyle);

            try
            {
                if (!DrawSectionStrip(SectionTitle, Detail()))
                    return;

                DrawBody(pathStyle);
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }
        }

#if !WPFMA_VRC_AVATARS
        private static string Detail()
        {
            return "needs the avatar SDK";
        }

        private static void DrawBody(GUIStyle pathStyle)
        {
            EditorGUILayout.HelpBox(
                "This needs the VRChat avatar SDK, which is not in this project. Install it from the Importer tab.",
                MessageType.Info);
        }
#else
        private static string Detail()
        {
            var targets = Targets();
            if (Request.Avatar == null)
                return "no avatar";

            return targets.Count == 0
                ? "nothing to toggle"
                : targets.Count + (targets.Count == 1 ? " object" : " objects");
        }

        private static List<GameObject> Targets()
        {
            if (!useSelection)
                return Request.Targets.Where(t => t != null).ToList();

            return Selection.gameObjects
                .Where(o => o != null && !EditorUtility.IsPersistent(o))
                .ToList();
        }

        private static void DrawBody(GUIStyle pathStyle)
        {
            if (Request.Avatar == null || !StillInside(Request.Avatar))
                Request.Avatar = ResolveAvatar() ?? Request.Avatar;

            Request.Avatar = (VRCAvatarDescriptor)EditorGUILayout.ObjectField(
                "Avatar", Request.Avatar, typeof(VRCAvatarDescriptor), true);

            Request.Name = EditorGUILayout.TextField("Name in menu", Request.Name);
            WPFMAToolDefaults.Load(Request);

            DrawMenuPicker();

            var targets = Targets();
            useSelection = EditorGUILayout.ToggleLeft(
                "Use whatever is selected  (" + targets.Count + ")", useSelection);

            if (!useSelection)
                DrawPinnedTargets();
            else
                DrawSelectionPreview(targets, pathStyle);

            EditorGUILayout.Space(4f);

            using (new EditorGUILayout.HorizontalScope())
            {
                Request.DefaultOn = EditorGUILayout.ToggleLeft("Starts on", Request.DefaultOn, GUILayout.Width(110f));
                Request.Saved = EditorGUILayout.ToggleLeft("Saved", Request.Saved, GUILayout.Width(80f));
                Request.AddToMenu = EditorGUILayout.ToggleLeft("Add to menu", Request.AddToMenu, GUILayout.Width(110f));
            }

            using (new EditorGUI.DisabledScope(!Request.AddToMenu))
                Request.Icon = (Texture2D)EditorGUILayout.ObjectField("Menu icon", Request.Icon, typeof(Texture2D), false);

            EditorGUILayout.Space(4f);
            showAdvanced = EditorGUILayout.Foldout(showAdvanced, "Advanced", true);
            if (showAdvanced)
            {
                EditorGUI.indentLevel++;

                Request.ParameterName = EditorGUILayout.TextField("Parameter name", Request.ParameterName);
                EditorGUILayout.LabelField(
                    string.IsNullOrWhiteSpace(Request.ParameterName)
                        ? "Empty means it is taken from the menu name."
                        : "Synced as '" + Request.ParameterName.Trim() + "'.",
                    Hint(FaintText));

                Request.WriteDefaults = (WPFMAToggleCreator.WriteDefaults)EditorGUILayout.EnumPopup(
                    "Write defaults", Request.WriteDefaults);

                Request.Synced = EditorGUILayout.ToggleLeft("Sync over the network", Request.Synced);
                if (!Request.Synced)
                    EditorGUILayout.LabelField(new GUIContent("Local only, costs no bits.", "Local only - nobody else sees it change, and it costs no sync bits."), Hint(FaintText));

                Request.Combined = EditorGUILayout.ToggleLeft(new GUIContent("Shared toggles layer",
                    "Every toggle shares one layer instead of adding its own. Fewer layers is better for performance. " +
                    "Off gives it a layer of its own, the old way."), Request.Combined);

                DrawClipSource();
                DrawFolderPicker();

                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space(6f);

            WPFMAToolDefaults.Save(Request);
            Request.Targets = targets;
            var problems = WPFMAToggleCreator.Validate(Request);

            foreach (var problem in problems.Take(3))
                EditorGUILayout.LabelField(problem, Hint(WarnAmber));

            using (new EditorGUI.DisabledScope(problems.Count > 0))
            {
                if (GUILayout.Button("Create toggle", GUILayout.Height(26f)))
                    Run();
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, Hint(statusIsError ? WarnAmber : OkGreen));

            foreach (var note in notes)
                EditorGUILayout.LabelField(note, Hint(FaintText));

            DrawCombineExisting();
        }

        /// <summary>Offers to move the avatar's existing simple toggle layers into the shared layer.</summary>
        private static void DrawCombineExisting()
        {
            var controller = Request.Avatar != null ? WPFMAToggleCreator.FindFxController(Request.Avatar) as UnityEditor.Animations.AnimatorController : null;
            if (controller == null)
                return;

            int dirty = EditorUtility.GetDirtyCount(controller);
            if (controller != combinableFor || dirty != combinableDirty)
            {
                combinableFor = controller;
                combinableDirty = dirty;
                combinableCount = WPFMAToggleCreator.Combinable(controller).Count;
            }

            if (combinableCount == 0)
                return;

            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField(
                combinableCount + " toggle layer(s) on this avatar can share one layer and work exactly the same.",
                Hint(WarnAmber));
            if (GUILayout.Button("Combine " + combinableCount + " toggle layer(s) into one", GUILayout.Height(22f)))
            {
                var avatar = Request.Avatar;
                EditorApplication.delayCall += () =>
                {
                    status = WPFMAChangeLog.Run("Toggle creator", "Combine toggles on '" + avatar.name + "'",
                        new[] { AssetDatabase.GetAssetPath(controller) }, false, () => WPFMAToggleCreator.CombineExisting(avatar));
                    statusIsError = false;
                    notes = new List<string>();
                    combinableFor = null;
                    Debug.Log("[WPFMA-SDK] " + status);
                };
            }
        }

        private static void DrawMenuPicker()
        {
            using (new EditorGUI.DisabledScope(!Request.AddToMenu))
            {
                var entries = WPFMAToggleCreator.EnumerateMenus(Request.Avatar);
                if (entries.Count == 0)
                {
                    EditorGUILayout.LabelField("Menu", "no expressions menu on this avatar");
                    return;
                }

                var current = WPFMAToggleCreator.ResolveMenu(Request);
                int index = Mathf.Max(0, entries.FindIndex(e => e.Menu == current));

                using (new EditorGUILayout.HorizontalScope())
                {
                    var labels = entries.Select(e => new GUIContent(e.Label)).ToArray();
                    int picked = EditorGUILayout.Popup(new GUIContent("Menu"), index, labels);
                    if (picked != index)
                        Request.Menu = entries[picked].Menu;

                    if (GUILayout.Button("+", GUILayout.Width(24f)))
                        AddSubmenu(entries[Mathf.Clamp(picked, 0, entries.Count - 1)].Menu);
                }

                var chosen = entries[Mathf.Clamp(index, 0, entries.Count - 1)];
                if (chosen.Full)
                    EditorGUILayout.LabelField("That menu is full. Use + to add a submenu.", Hint(WarnAmber));
            }
        }

        private static void AddSubmenu(VRCExpressionsMenu parent)
        {
            string name = string.IsNullOrWhiteSpace(newMenuName) ? "New Menu" : newMenuName;

            string problem;
            var created = WPFMAToggleCreator.CreateSubmenu(parent, name, out problem);
            if (created == null)
            {
                status = problem;
                statusIsError = true;
                return;
            }

            Request.Menu = created;
            newMenuName = string.Empty;
            status = "Added submenu '" + created.name + "'.";
            statusIsError = false;
        }

        private static void DrawClipSource()
        {
            Request.UseExistingClips = EditorGUILayout.ToggleLeft("Use existing animations", Request.UseExistingClips);
            if (!Request.UseExistingClips)
                return;

            Request.ExistingOn = (AnimationClip)EditorGUILayout.ObjectField("ON clip", Request.ExistingOn, typeof(AnimationClip), false);
            Request.ExistingOff = (AnimationClip)EditorGUILayout.ObjectField("OFF clip", Request.ExistingOff, typeof(AnimationClip), false);

            EditorGUILayout.LabelField("Objects above are ignored; the clips decide what changes.", Hint(FaintText));
        }

        private static void DrawFolderPicker()
        {
            using (new EditorGUI.DisabledScope(Request.UseExistingClips))
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("New clips go to", GUILayout.Width(EditorGUIUtility.labelWidth - 14f));
                EditorGUILayout.SelectableLabel(
                    string.IsNullOrEmpty(Request.Folder) ? "beside the FX controller" : Request.Folder,
                    EditorStyles.miniLabel, GUILayout.Height(16f));

                if (GUILayout.Button("Pick", GUILayout.Width(50f)))
                {
                    string picked = EditorUtility.OpenFolderPanel("Folder for new animations", "Assets", string.Empty);
                    if (!string.IsNullOrEmpty(picked))
                    {
                        string root = System.IO.Path.GetFullPath("Assets").Replace('\\', '/');
                        string full = picked.Replace('\\', '/');
                        if (full.StartsWith(root, System.StringComparison.OrdinalIgnoreCase))
                            Request.Folder = "Assets" + full.Substring(root.Length);
                        else
                            status = "That folder is outside the project, so assets cannot be written there.";
                    }
                }

                if (GUILayout.Button("Reset", GUILayout.Width(55f)))
                    Request.Folder = null;
            }
        }

        private static void Run()
        {
            // Recorded in the Change log, so reverting it there also removes the clips it made.
            var avatar = Request.Avatar;
            var touched = new List<string>
            {
                AssetDatabase.GetAssetPath(WPFMAToggleCreator.FindFxController(avatar)),
                AssetDatabase.GetAssetPath(WPFMAToggleCreator.ResolveMenu(Request)),
                AssetDatabase.GetAssetPath(avatar.expressionParameters)
            }.Where(p => !string.IsNullOrEmpty(p)).Distinct().ToList();

            WPFMAToggleCreator.Result result = null;
            WPFMAChangeLog.Run("Toggle creator", "Create toggle '" + Request.Name + "'", touched, false,
                () => (result = WPFMAToggleCreator.Create(Request)).Message,
                () => result != null ? result.Created : null);

            status = result.Message;
            statusIsError = !result.Success;
            notes = result.Notes;

            if (result.Success)
                Debug.Log("[WPFMA-SDK] " + result.Message);
            else
                Debug.LogWarning("[WPFMA-SDK] Toggle not created: " + result.Message);
        }

        private static void DrawSelectionPreview(List<GameObject> targets, GUIStyle pathStyle)
        {
            if (targets.Count == 0)
            {
                EditorGUILayout.LabelField("Select the objects in the Hierarchy.", Hint(FaintText));
                return;
            }

            foreach (var target in targets.Take(6))
                EditorGUILayout.LabelField("   " + target.name, Hint(FaintText));

            if (targets.Count > 6)
                EditorGUILayout.LabelField("   and " + (targets.Count - 6) + " more", Hint(FaintText));
        }

        private static void DrawPinnedTargets()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Add selected", GUILayout.Width(110f)))
                {
                    foreach (var selected in Selection.gameObjects)
                    {
                        if (selected != null && !EditorUtility.IsPersistent(selected) && !Request.Targets.Contains(selected))
                            Request.Targets.Add(selected);
                    }
                }

                if (GUILayout.Button("Clear", GUILayout.Width(70f)))
                    Request.Targets.Clear();
            }

            for (int i = 0; i < Request.Targets.Count; i++)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    Request.Targets[i] = (GameObject)EditorGUILayout.ObjectField(Request.Targets[i], typeof(GameObject), true);
                    if (GUILayout.Button("-", GUILayout.Width(24f)))
                    {
                        Request.Targets.RemoveAt(i);
                        GUIUtility.ExitGUI();
                    }
                }
            }
        }

        private static bool StillInside(VRCAvatarDescriptor avatar)
        {
            var active = Selection.activeGameObject;
            return active == null || avatar == null || active.transform.IsChildOf(avatar.transform);
        }

        private static VRCAvatarDescriptor ResolveAvatar()
        {
            var active = Selection.activeGameObject;
            return active == null ? null : active.GetComponentInParent<VRCAvatarDescriptor>();
        }

        private static GUIStyle Hint(Color color)
        {
            return new GUIStyle(EditorStyles.miniLabel)
            {
                wordWrap = true,
                normal = { textColor = color }
            };
        }
#endif

        private static bool DrawSectionStrip(string title, string detail)
        {
            bool expanded = EditorPrefs.GetBool(ExpandedPrefKey, true);

            var rect = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), ToolbarEdge);

            GUI.Label(new Rect(rect.x + 8f, rect.y, 14f, rect.height), expanded ? "▾" : "▸",
                new GUIStyle(EditorStyles.label) { fontSize = 12, normal = { textColor = AccentBlue } });

            GUI.Label(new Rect(rect.x + 24f, rect.y, 240f, rect.height), title,
                new GUIStyle(EditorStyles.label) { fontSize = 12, normal = { textColor = AccentBlue } });

            GUI.Label(new Rect(rect.xMax - 204f, rect.y, 200f, rect.height), detail,
                new GUIStyle(EditorStyles.label)
                {
                    fontSize = 11,
                    alignment = TextAnchor.MiddleRight,
                    normal = { textColor = FaintText }
                });

            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);

            var evt = Event.current;
            if (evt.type == EventType.MouseDown && evt.button == 0 && rect.Contains(evt.mousePosition))
            {
                expanded = !expanded;
                EditorPrefs.SetBool(ExpandedPrefKey, expanded);
                evt.Use();
            }

            return expanded;
        }
    }
}
#endif
