// 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;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace WPFMA.Editor
{
    internal sealed class WPFMAInstallPromptWindow : EditorWindow
    {
        internal const int AddChoice = 0;
        internal const int NotNowChoice = 1;
        internal const int NeverChoice = 2;

        private const float Width = 540f;
        private const float RowHeight = 22f;

        private static readonly Dictionary<string, string> FriendlyNames = new Dictionary<string, string>
        {
            { "com.wpfma.sdk", "WPFMA-SDK" },
            { "com.vrchat.base", "VRChat SDK Base" },
            { "com.vrchat.avatars", "VRChat Avatar SDK" },
            { "com.vrchat.worlds", "VRChat World SDK" },
            { "com.unity.timeline", "Timeline" },
            { "com.unity.formats.fbx", "FBX Exporter" },
            { "com.autodesk.fbx", "Autodesk FBX SDK" },
            { "com.facs01.facs_utilities", "FACS Utilities" },
            { "nadena.dev.ndmf", "NDMF" },
            { "nadena.dev.modular-avatar", "Modular Avatar" },
            { "dev.limitex.avatar-compressor", "Avatar Compressor" },
            { "vrchat.jordo.easyquestswitch", "EasyQuestSwitch" },
            { "vrchat.blackstartx.gesture-manager", "Gesture Manager" }
        };

        private static int picked;

        private string[] packages = new string[0];

        [NonSerialized] private GUIStyle titleStyle;
        [NonSerialized] private GUIStyle bodyStyle;
        [NonSerialized] private GUIStyle nameStyle;
        [NonSerialized] private GUIStyle idStyle;
        [NonSerialized] private GUIStyle hintStyle;
        [NonSerialized] private GUIStyle buttonStyle;
        [NonSerialized] private GUIStyle linkStyle;

        internal static int Ask(IList<string> pending)
        {
            picked = NotNowChoice;

            var window = CreateInstance<WPFMAInstallPromptWindow>();
            window.packages = pending.ToArray();
            window.titleContent = new GUIContent("WPFMA-SDK Setup");
            window.wantsMouseMove = true;

            var size = new Vector2(Width, 208f + window.packages.Length * RowHeight);
            window.minSize = size;
            window.maxSize = size;

            var main = EditorGUIUtility.GetMainWindowPosition();
            window.position = new Rect(
                main.x + (main.width - size.x) * 0.5f,
                main.y + (main.height - size.y) * 0.5f,
                size.x, size.y);

            window.ShowModal();
            return picked;
        }

        private void OnGUI()
        {
            EnsureStyles();

            var e = Event.current;
            if (e.type == EventType.MouseMove)
                Repaint();

            if (e.type == EventType.KeyDown && e.keyCode == KeyCode.Escape)
            {
                Choose(NotNowChoice);
                return;
            }

            float width = position.width;
            EditorGUI.DrawRect(new Rect(0f, 0f, width, position.height), WPFMAProjectKindWindow.Background);

            GUI.Label(new Rect(24f, 18f, width - 48f, 28f), "Some packages are missing", titleStyle);
            GUI.Label(new Rect(24f, 48f, width - 48f, 36f),
                "This project already has its own VRChat SDK. WPFMA-SDK can add the tools it needs that " +
                "aren't here yet. Nothing you already have gets replaced.",
                bodyStyle);

            float listTop = 94f;
            float listHeight = packages.Length * RowHeight + 16f;
            var list = new Rect(24f, listTop, width - 48f, listHeight);
            EditorGUI.DrawRect(list, WPFMAProjectKindWindow.Border);
            EditorGUI.DrawRect(new Rect(list.x + 1f, list.y + 1f, list.width - 2f, list.height - 2f),
                WPFMAProjectKindWindow.Panel);
            EditorGUI.DrawRect(new Rect(list.x + 1f, list.y + 1f, 3f, list.height - 2f), WPFMAProjectKindWindow.AccentDim);

            float y = list.y + 8f;
            foreach (var package in packages)
            {
                string friendly;
                if (!FriendlyNames.TryGetValue(package, out friendly))
                    friendly = package;

                EditorGUI.DrawRect(new Rect(list.x + 18f, y + 9f, 4f, 4f), WPFMAProjectKindWindow.Accent);
                GUI.Label(new Rect(list.x + 30f, y, 220f, RowHeight), friendly, nameStyle);
                if (friendly != package)
                    GUI.Label(new Rect(list.x + 250f, y, list.width - 266f, RowHeight), package, idStyle);
                y += RowHeight;
            }

            float hintTop = list.yMax + 10f;
            GUI.Label(new Rect(24f, hintTop, width - 48f, 18f),
                "Using the Creator Companion? You can add these there instead.",
                hintStyle);

            float buttonTop = hintTop + 34f;
            var add = new Rect(width - 24f - 170f, buttonTop, 170f, 30f);
            var notNow = new Rect(add.x - 10f - 100f, buttonTop, 100f, 30f);
            var never = new Rect(24f, buttonTop, 160f, 30f);

            if (DrawButton(add, "Add what's missing", true))
                Choose(AddChoice);
            else if (DrawButton(notNow, "Not now", false))
                Choose(NotNowChoice);
            else if (DrawLink(never, "Never for this project"))
                Choose(NeverChoice);
        }

        private bool DrawButton(Rect rect, string label, bool primary)
        {
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition);

            if (primary)
            {
                EditorGUI.DrawRect(rect, hover ? WPFMAProjectKindWindow.Accent : WPFMAProjectKindWindow.AccentDim);
                buttonStyle.normal.textColor = hover ? WPFMAProjectKindWindow.AccentText : WPFMAProjectKindWindow.TitleText;
            }
            else
            {
                EditorGUI.DrawRect(rect, hover ? WPFMAProjectKindWindow.AccentDim : WPFMAProjectKindWindow.Border);
                EditorGUI.DrawRect(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f),
                    hover ? WPFMAProjectKindWindow.PanelHover : WPFMAProjectKindWindow.Background);
                buttonStyle.normal.textColor = WPFMAProjectKindWindow.BodyText;
            }

            GUI.Label(rect, label, buttonStyle);
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            return Clicked(rect);
        }

        private bool DrawLink(Rect rect, string label)
        {
            bool hover = rect.Contains(Event.current.mousePosition);
            linkStyle.normal.textColor = hover ? WPFMAProjectKindWindow.BodyText : WPFMAProjectKindWindow.DimText;
            GUI.Label(rect, label, linkStyle);

            if (hover)
            {
                var size = linkStyle.CalcSize(new GUIContent(label));
                EditorGUI.DrawRect(new Rect(rect.x, rect.center.y + size.y * 0.5f - 1f, size.x, 1f),
                    WPFMAProjectKindWindow.BodyText);
            }

            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            return Clicked(rect);
        }

        private static bool Clicked(Rect rect)
        {
            var e = Event.current;
            if (e.type != EventType.MouseDown || e.button != 0 || !rect.Contains(e.mousePosition))
                return false;

            e.Use();
            return true;
        }

        private void Choose(int choice)
        {
            picked = choice;
            Close();
            GUIUtility.ExitGUI();
        }

        private void EnsureStyles()
        {
            if (titleStyle != null)
                return;

            titleStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 18,
                normal = { textColor = WPFMAProjectKindWindow.TitleText }
            };

            bodyStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 12,
                wordWrap = true,
                normal = { textColor = WPFMAProjectKindWindow.BodyText }
            };

            nameStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 12,
                alignment = TextAnchor.MiddleLeft,
                normal = { textColor = WPFMAProjectKindWindow.TitleText }
            };

            idStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 11,
                alignment = TextAnchor.MiddleRight,
                normal = { textColor = WPFMAProjectKindWindow.DimText }
            };

            hintStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 11,
                normal = { textColor = WPFMAProjectKindWindow.DimText }
            };

            buttonStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 12,
                alignment = TextAnchor.MiddleCenter
            };

            linkStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 11,
                alignment = TextAnchor.MiddleLeft
            };
        }
    }
}
#endif
