// 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 UnityEditor;
using UnityEngine;

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

namespace WPFMA
{
    internal static class WPFMAAvatarSetupSection
    {
        private const string SectionTitle = "Avatar setup";
        private const string ExpandedPrefKey = "WPFMA.Tools.AvatarSetupExpanded";

        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 Color MetaText => WPFMATheme.Shift(new Color(143f / 255f, 163f / 255f, 181f / 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 WPFMAAvatarSetup.Request Request = new WPFMAAvatarSetup.Request();
        private static GameObject folderFor;
        private static string status;
        private static bool statusIsError;
        private static List<string> notes = new List<string>();
#endif

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds)
                return;

            EditorGUILayout.Space(10f);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(sectionStyle);

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

                DrawBody();
            }
            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()
        {
            EditorGUILayout.HelpBox(
                "This needs the VRChat avatar SDK, which is not in this project yet.",
                MessageType.Info);
        }
#else
        private static string Detail()
        {
            var root = WPFMAAvatarSetup.ResolveRoot(Selection.activeGameObject);
            if (root == null)
                return "nothing selected";

            return root.GetComponent<VRCAvatarDescriptor>() != null ? root.name + " (has descriptor)" : root.name;
        }

        private static void DrawBody()
        {
            EditorGUILayout.LabelField(new GUIContent("Make a model into a VRChat avatar.", "Turns a freshly imported model into a VRChat avatar: adds the Avatar Descriptor and makes a new " + "FX controller, Expressions Menu and Expression Parameters, all hooked up."), Hint(MetaText));
            EditorGUILayout.Space(4f);

            var selected = Selection.activeGameObject;
            if (selected != null && EditorUtility.IsPersistent(selected))
            {
                DrawProjectAsset(selected);
                return;
            }

            var root = WPFMAAvatarSetup.ResolveRoot(selected);
            if (root != Request.Root)
            {
                Request.Root = root;
                status = null;
                notes = new List<string>();
            }

            if (root == null)
            {
                EditorGUILayout.LabelField(new GUIContent("Select a model.", "Select the model in the Hierarchy, or its FBX in the Project."), Hint(FaintText));
                return;
            }

            if (folderFor != root)
            {
                folderFor = root;
                Request.Folder = WPFMAAvatarSetup.DefaultFolder(root);
            }

            EditorGUILayout.LabelField("Model", root.name, EditorStyles.boldLabel);

            DrawRig(root);
            DrawPlan(root);
            DrawFolder();

            EditorGUILayout.Space(4f);
            WPFMAToolDefaults.Load(Request);
            Request.ReplaceExisting = EditorGUILayout.ToggleLeft(
                "Replace files that are already set on the descriptor", Request.ReplaceExisting);

            using (new EditorGUI.DisabledScope(!WPFMAAvatarSetup.HasEyes(root)))
            {
                Request.ViewFromEyes = EditorGUILayout.ToggleLeft(
                    WPFMAAvatarSetup.HasEyes(root)
                        ? "Put the view position between the eyes"
                        : "Put the view position between the eyes  (no eye bones found)",
                    Request.ViewFromEyes);
            }

            Request.LipSync = EditorGUILayout.ToggleLeft(new GUIContent("Lip sync", "Set up lip sync from the model's viseme blendshapes."), Request.LipSync);
            Request.EyeLook = EditorGUILayout.ToggleLeft(new GUIContent("Eye look and blink", "Set up eye look and blink."), Request.EyeLook);
            WPFMAToolDefaults.Save(Request);

            EditorGUILayout.Space(6f);

            var problems = WPFMAAvatarSetup.Validate(Request);
            foreach (var problem in problems)
                EditorGUILayout.LabelField(problem, Hint(WarnAmber));

            using (new EditorGUI.DisabledScope(problems.Count > 0))
            {
                if (GUILayout.Button("Set up avatar", GUILayout.Height(26f)))
                {
                    var request = Request;
                    var descriptor = request.Root != null ? request.Root.GetComponent<VRCAvatarDescriptor>() : null;
                    var existing = new List<string>();
                    if (descriptor != null)
                        existing.AddRange(WPFMAChangeLog.AssetPaths(new UnityEngine.Object[]
                        {
                            WPFMAAvatarSetup.CurrentFx(descriptor), WPFMAAvatarSetup.CurrentMenu(descriptor), WPFMAAvatarSetup.CurrentParameters(descriptor)
                        }));
                    EditorApplication.delayCall += () =>
                    {
                        var before = WPFMAChangeLog.FilesIn(request.Folder);
                        WPFMAChangeLog.Run("Avatar setup", "Set up '" + request.Root.name + "'", existing, true,
                            () => { Run(request); return status; }, () => WPFMAChangeLog.NewFiles(request.Folder, before));
                    };
                }
            }

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

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

        private static void DrawProjectAsset(GameObject asset)
        {
            EditorGUILayout.LabelField("Model", asset.name + "  (in the Project)", EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Place it in the scene first, then set it up from there.", Hint(FaintText));

            DrawRig(asset);

            if (GUILayout.Button("Place in scene", GUILayout.Height(24f), GUILayout.Width(160f)))
            {
                EditorApplication.delayCall += () => WPFMAChangeLog.Run("Avatar setup", "Place '" + asset.name + "' in the scene", null, true, () =>
                {
                    var instance = PrefabUtility.InstantiatePrefab(asset) as GameObject;
                    if (instance == null)
                        return "Could not place it.";

                    Undo.RegisterCreatedObjectUndo(instance, "Place " + asset.name);
                    Selection.activeGameObject = instance;
                    return "Placed '" + asset.name + "'.";
                });
            }
        }

        private static void DrawRig(GameObject model)
        {
            var importer = WPFMAAvatarSetup.SourceModel(model);
            bool humanoid = importer != null
                ? importer.animationType == ModelImporterAnimationType.Human
                : WPFMAAvatarSetup.IsHumanoid(model);

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Rig", humanoid ? "Humanoid" : "Not Humanoid",
                    Hint(humanoid ? OkGreen : WarnAmber));

                if (!humanoid && importer != null &&
                    GUILayout.Button("Make it Humanoid", GUILayout.Width(130f)))
                {
                    EditorApplication.delayCall += () => WPFMAChangeLog.Run("Avatar setup", "Make '" + model.name + "' Humanoid",
                        new[] { importer.assetPath + ".meta" }, false, () => { WPFMAAvatarSetup.MakeHumanoid(importer); return "Rig set to Humanoid."; });
                }
            }

            if (!humanoid)
            {
                EditorGUILayout.LabelField(new GUIContent("Full body and gestures need Humanoid.", "Most VRChat avatars need a Humanoid rig for full body, gestures and sitting to work."), Hint(FaintText));
            }
        }

        private static void DrawPlan(GameObject root)
        {
            var descriptor = root.GetComponent<VRCAvatarDescriptor>();

            PlanRow("Avatar Descriptor", descriptor != null ? "already there" : "will be added", descriptor != null);
            PlanRow("FX controller", Plan(WPFMAAvatarSetup.CurrentFx(descriptor), "FX.controller"),
                WPFMAAvatarSetup.CurrentFx(descriptor) != null && !Request.ReplaceExisting);
            PlanRow("Expressions Menu", Plan(WPFMAAvatarSetup.CurrentMenu(descriptor), "Menu.asset"),
                WPFMAAvatarSetup.CurrentMenu(descriptor) != null && !Request.ReplaceExisting);
            PlanRow("Expression Parameters", Plan(WPFMAAvatarSetup.CurrentParameters(descriptor), "Parameters.asset"),
                WPFMAAvatarSetup.CurrentParameters(descriptor) != null && !Request.ReplaceExisting);
        }

        private static string Plan(Object current, string suffix)
        {
            if (current != null && !Request.ReplaceExisting)
                return "keeps " + current.name;

            return "new " + WPFMAPaths.SafeFileName(Request.Root.name) + " " + suffix;
        }

        private static void PlanRow(string label, string value, bool kept)
        {
            EditorGUILayout.LabelField(label, value, Hint(kept ? FaintText : AccentBlue));
        }

        private static void DrawFolder()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Save files to", GUILayout.Width(EditorGUIUtility.labelWidth - 4f));
                EditorGUILayout.SelectableLabel(Request.Folder ?? string.Empty, EditorStyles.miniLabel, GUILayout.Height(16f));

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

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

        private static void Run(WPFMAAvatarSetup.Request request)
        {
            var result = WPFMAAvatarSetup.Run(request);
            status = result.Message;
            statusIsError = !result.Success;
            notes = result.Notes;

            if (result.Success)
            {
                Debug.Log("[WPFMA-SDK] " + result.Message);
                Selection.activeObject = result.Descriptor;
            }
            else
            {
                Debug.LogWarning("[WPFMA-SDK] Avatar setup did not run: " + result.Message);
            }
        }

        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 - 244f, rect.y, 240f, 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
