// 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.Team
{
    /// <summary>
    /// Everything about a session is decided here, once, before connecting: how to connect, what is shared and
    /// what to trust. The choices are remembered, so next time it is one click. Opened again from the Team tab
    /// while connected, it shows the options that can change during a session.
    /// </summary>
    internal sealed class TeamSetupWindow : EditorWindow
    {
        internal enum Mode
        {
            Host,
            Join,
            Settings
        }

        private const string DirectKey = "WPFMA.Team.Direct";
        private const string AddressKey = "WPFMA.Team.LastAddress";

        private static Color Background => WPFMA.Editor.WPFMAProjectKindWindow.Background;
        private static Color Panel => WPFMA.Editor.WPFMAProjectKindWindow.Panel;
        private static Color PanelHover => WPFMA.Editor.WPFMAProjectKindWindow.PanelHover;
        private static Color Border => WPFMA.Editor.WPFMAProjectKindWindow.Border;
        private static Color Accent => WPFMA.Editor.WPFMAProjectKindWindow.Accent;
        private static Color AccentDim => WPFMA.Editor.WPFMAProjectKindWindow.AccentDim;
        private static Color AccentText => WPFMA.Editor.WPFMAProjectKindWindow.AccentText;
        private static Color TitleText => WPFMA.Editor.WPFMAProjectKindWindow.TitleText;
        private static Color BodyText => WPFMA.Editor.WPFMAProjectKindWindow.BodyText;
        private static Color DimText => WPFMA.Editor.WPFMAProjectKindWindow.DimText;
        private static readonly Color Warn = new Color(239f / 255f, 159f / 255f, 39f / 255f);

        [SerializeField] private Mode mode;
        [SerializeField] private string code = string.Empty;
        [SerializeField] private string password = string.Empty;
        [SerializeField] private string address = string.Empty;
        [SerializeField] private bool direct;
        [SerializeField] private Vector2 scroll;
        [NonSerialized] private List<string> folders;
        [NonSerialized] private List<string> paid;
        [NonSerialized] private GUIStyle titleStyle, body, dim, section, rowTitle, rowBody, buttonText, field;

        internal static void Open(Mode mode, string code = null)
        {
            foreach (var old in Resources.FindObjectsOfTypeAll<TeamSetupWindow>())
                old.Close();

            var window = CreateInstance<TeamSetupWindow>();
            window.mode = mode;
            window.code = code ?? string.Empty;
            window.direct = EditorPrefs.GetBool(DirectKey, false);
            window.address = EditorPrefs.GetString(AddressKey, string.Empty);
            window.titleContent = new GUIContent(mode == Mode.Settings ? "Team settings" : mode == Mode.Host ? "Host a Team session" : "Join a Team session");
            var size = new Vector2(480f, mode == Mode.Settings ? 520f : 640f);
            window.minSize = 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.ShowUtility();
        }

        private void OnEnable()
        {
            wantsMouseMove = true;
        }

        private void OnGUI()
        {
            Styles();
            var e = Event.current;
            if (e.type == EventType.MouseMove)
                Repaint();
            EditorGUI.DrawRect(new Rect(0f, 0f, position.width, position.height), Background);

            GUILayout.Space(16f);
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(20f);
                using (new GUILayout.VerticalScope())
                {
                    GUILayout.Label(mode == Mode.Settings ? "Team settings" : mode == Mode.Host ? "Host a session" : "Join a session", titleStyle);
                    GUILayout.Label(Subtitle(), body);
                    GUILayout.Space(10f);

                    scroll = GUILayout.BeginScrollView(scroll, GUIStyle.none, GUI.skin.verticalScrollbar);
                    if (mode != Mode.Settings)
                        DrawConnection();
                    if (mode == Mode.Host || (mode == Mode.Settings && TeamSession.IsHost))
                        DrawSharing();
                    DrawOptions();
                    GUILayout.Space(8f);
                    GUILayout.EndScrollView();

                    GUILayout.Space(8f);
                    DrawFooter();
                    GUILayout.Space(14f);
                }
                GUILayout.Space(20f);
            }
        }

        private string Subtitle()
        {
            switch (mode)
            {
                case Mode.Host:
                    return "Your friend joins your project. Your files and scenes are the reference: theirs are matched to yours.";
                case Mode.Join:
                    return "You join your friend's project. Your files are matched to the host's (anything replaced is backed up to WPFMA-Snapshots/Team).";
                default:
                    return "Changes apply straight away and are remembered for next time.";
            }
        }

        // ---- Connection ---------------------------------------------------------------------------------------------

        private void DrawConnection()
        {
            Section("Connection");
            string name = Field("Your name", EditorPrefs.GetString("WPFMA.Team.Name", string.Empty));
            if (name != EditorPrefs.GetString("WPFMA.Team.Name", string.Empty))
                TeamSession.DisplayName = name;

            if (Choice("Over the internet", "reqid.io only helps you find each other; everything else goes straight between your PCs.", !direct))
                direct = false;
            if (Choice("Same home network or Tailscale", mode == Mode.Host
                    ? "No website. Your friend types your address, port and code."
                    : "No website. Type the host's address (their Tailscale IP when using Tailscale) and port.", direct))
                direct = true;

            if (mode == Mode.Join)
            {
                if (direct)
                    address = Field("Host address", address, "like 100.64.1.2:" + TeamSession.Port);
                code = Field("Session code", code).ToUpperInvariant();
            }
            password = PasswordField(mode == Mode.Host ? "Password (optional)" : "Password (if they set one)", password);
        }

        // ---- Sharing (host) -----------------------------------------------------------------------------------------

        private void DrawSharing()
        {
            if (folders == null)
            {
                folders = TeamFiles.TopFolders();
                paid = TeamFiles.DetectLicensed();
            }

            Section("What you share");
            GUILayout.Label("Ticked folders are sent to your friend and kept in sync. Untick anything you bought (avatars, shaders, tools) " +
                            "unless its license lets you share it: your friend installs their own copy. Packages are never sent.", dim);
            GUILayout.Space(4f);

            var excluded = TeamFiles.Excluded;
            bool changed = false;
            foreach (var folder in folders)
            {
                bool shared = !excluded.Contains(folder);
                string label = folder.Substring("Assets/".Length);
                bool now = Switch(label, paid.Contains(folder) ? "Looks like paid content" : null, shared, true);
                if (now == shared)
                    continue;
                changed = true;
                if (now)
                    excluded.Remove(folder);
                else
                    excluded.Add(folder);
            }

            if (changed)
            {
                TeamFiles.Excluded = excluded;
                TeamFiles.ShareConfirmed = true;
                if (TeamSession.IsLinked && TeamSession.IsHost)
                    TeamSession.Send(new TeamMessage { t = "rules", a = excluded.ToArray() });
            }
        }

        // ---- Options -----------------------------------------------------------------------------------------------

        private void DrawOptions()
        {
            Section("Options");
            bool host = mode == Mode.Host || (mode == Mode.Settings && TeamSession.IsHost);
            bool live = mode == Mode.Settings && TeamSession.IsLinked;

            bool trust = Switch("Trust scripts and plugins from my friend",
                "Their .cs scripts, DLLs and assembly files are added and Unity runs them, like anything you import. Leave off " +
                "unless you trust them; scripts then wait for you in the Team tab.",
                live ? TeamFiles.TrustCode : TeamFiles.TrustOnConnect);
            if (trust != (live ? TeamFiles.TrustCode : TeamFiles.TrustOnConnect))
            {
                TeamFiles.TrustOnConnect = trust;
                if (live)
                    TeamFiles.TrustCode = trust;
            }

            if (!host)
            {
                bool get = Switch("Get the host's project automatically", "No extra prompt when you join or reconnect.", TeamFiles.AutoGetProject);
                if (get != TeamFiles.AutoGetProject)
                    TeamFiles.AutoGetProject = get;

                bool install = Switch("Install free packages the host uses", "VRCFury, Modular Avatar, lilToon, Poiyomi Toon and similar. Paid ones are listed for you to get.", TeamProject.AutoInstall);
                if (install != TeamProject.AutoInstall)
                    TeamProject.AutoInstall = install;

                bool follow = Switch("Follow the host to every scene", "Off: you start in the host's scene, then work wherever you like. Opening a scene a teammate is in joins them.", TeamScene.FollowPreference);
                if (follow != TeamScene.FollowPreference)
                    TeamScene.FollowPreference = follow;
            }

            bool locks = Switch("Make what my friend has selected read-only for me", "So you never both edit the same object.", TeamLocks.Enabled);
            if (locks != TeamLocks.Enabled)
                TeamLocks.Enabled = locks;

            bool save = Switch("Save changed assets automatically", "Animators, menus and clips reach your friend without pressing Save.", TeamFiles.AutoSave);
            if (save != TeamFiles.AutoSave)
                TeamFiles.AutoSave = save;

            bool standIns = Switch("Show a stand-in for shaders I don't have", "Instead of pink. Only how it looks for you; files are never changed.", TeamStandIns.Enabled);
            if (standIns != TeamStandIns.Enabled)
                TeamStandIns.Enabled = standIns;

            bool presence = Switch("Show my friend's camera and selection", null, TeamView.ShowCamera && TeamView.ShowSelection);
            if (presence != (TeamView.ShowCamera && TeamView.ShowSelection))
            {
                TeamView.ShowCamera = presence;
                TeamView.ShowSelection = presence;
                TeamView.Repaint();
            }

            bool toasts = Switch("Show notes in the Scene view", "Chat, reconnects and uploads. Edits never pop up; they're in the Change log.", TeamToasts.Enabled);
            if (toasts != TeamToasts.Enabled)
                TeamToasts.Enabled = toasts;

            if (mode != Mode.Settings)
            {
                int port = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Port", "Only change this if something else on your PC uses it."), TeamSession.Port), 1024, 65535);
                if (port != TeamSession.Port)
                    TeamSession.Port = port;
            }
        }

        // ---- Footer ------------------------------------------------------------------------------------------------

        private void DrawFooter()
        {
            if (mode == Mode.Settings)
            {
                using (new GUILayout.HorizontalScope())
                {
                    foreach (var peer in TeamSession.IsHost ? TeamSession.Peers.Where(p => p.Link != null).ToList() : new List<TeamPeer>())
                    {
                        if (!SmallButton("Remove " + peer.Name))
                            continue;
                        if (EditorUtility.DisplayDialog("Team", "Remove " + peer.Name + " from the session? Everyone else stays.", "Remove", "Cancel"))
                        {
                            TeamSession.Kick(peer);
                            Close();
                            GUIUtility.ExitGUI();
                        }
                    }
                    if (TeamSession.IsLinked && SmallButton("Check everything matches"))
                        TeamFiles.StartCheck();
                    GUILayout.FlexibleSpace();
                    if (BigButton("Done", 120f))
                    {
                        Close();
                        GUIUtility.ExitGUI();
                    }
                }
                return;
            }

            string problem = Problem();
            if (problem != null)
                GUILayout.Label(problem, new GUIStyle(dim) { normal = { textColor = Warn } });

            using (new GUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                using (new EditorGUI.DisabledScope(problem != null))
                {
                    if (BigButton(mode == Mode.Host ? "Start session" : "Join", 160f) && problem == null)
                        Go();
                }
            }
        }

        private string Problem()
        {
            if (mode == Mode.Join && code.Count(char.IsLetterOrDigit) < 4)
                return "Type the session code your friend gave you.";
            if (mode == Mode.Join && direct && string.IsNullOrWhiteSpace(address))
                return "Type the host's address.";
            return null;
        }

        private void Go()
        {
            EditorPrefs.SetBool(DirectKey, direct);
            if (direct && mode == Mode.Join)
                EditorPrefs.SetString(AddressKey, address.Trim());
            TeamFiles.ShareConfirmed = true;

            string pwd = password, sessionCode = code, target = address.Trim();
            bool viaAddress = direct;
            var chosen = mode;
            EditorApplication.delayCall += () =>
            {
                if (chosen == Mode.Host)
                {
                    if (viaAddress)
                        TeamSession.StartHostDirect(pwd);
                    else
                        TeamSession.StartHost(pwd);
                }
                else if (viaAddress)
                    TeamSession.JoinAddress(target, sessionCode, pwd);
                else
                    TeamSession.Join(sessionCode, pwd);
            };
            Close();
            GUIUtility.ExitGUI();
        }

        // ---- Drawing helpers ---------------------------------------------------------------------------------------

        private void Section(string text)
        {
            GUILayout.Space(10f);
            GUILayout.Label(text, section);
            var line = GUILayoutUtility.GetRect(1f, 1f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(line, Border);
            GUILayout.Space(6f);
        }

        private string Field(string label, string value, string placeholder = null)
        {
            GUILayout.Label(label, rowBody);
            string result = EditorGUILayout.TextField(value ?? string.Empty, field, GUILayout.Height(22f));
            if (string.IsNullOrEmpty(result) && placeholder != null)
                GUILayout.Label(placeholder, dim);
            GUILayout.Space(4f);
            return result;
        }

        private string PasswordField(string label, string value)
        {
            GUILayout.Label(label, rowBody);
            string result = EditorGUILayout.PasswordField(value ?? string.Empty, field, GUILayout.Height(22f));
            GUILayout.Space(4f);
            return result;
        }

        /// <summary>A clickable row with a switch on the right.</summary>
        private bool Switch(string label, string detail, bool value, bool compact = false)
        {
            float height = compact ? 26f : (string.IsNullOrEmpty(detail) ? 30f : 30f + rowBody.CalcHeight(new GUIContent(detail), position.width - 120f));
            var rect = GUILayoutUtility.GetRect(1f, height, GUILayout.ExpandWidth(true));
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition);
            EditorGUI.DrawRect(rect, hover ? PanelHover : Panel);

            var knob = new Rect(rect.xMax - 46f, rect.y + 7f, 34f, 16f);
            EditorGUI.DrawRect(knob, value ? Accent : Border);
            EditorGUI.DrawRect(new Rect(value ? knob.xMax - 14f : knob.x + 2f, knob.y + 2f, 12f, 12f), value ? AccentText : DimText);

            GUI.Label(new Rect(rect.x + 10f, rect.y + 5f, rect.width - 70f, 20f), label, rowTitle);
            if (!compact && !string.IsNullOrEmpty(detail))
                GUI.Label(new Rect(rect.x + 10f, rect.y + 24f, rect.width - 70f, height - 26f), detail, rowBody);
            else if (compact && !string.IsNullOrEmpty(detail))
                GUI.Label(new Rect(rect.x + 10f + rowTitle.CalcSize(new GUIContent(label)).x + 8f, rect.y + 5f, 200f, 20f), detail, new GUIStyle(rowBody) { normal = { textColor = Warn } });

            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            GUILayout.Space(3f);
            if (e.type == EventType.MouseDown && e.button == 0 && hover)
            {
                e.Use();
                GUI.changed = true;
                return !value;
            }
            return value;
        }

        private bool Choice(string label, string detail, bool selected)
        {
            float height = 30f + rowBody.CalcHeight(new GUIContent(detail), position.width - 100f);
            var rect = GUILayoutUtility.GetRect(1f, height, GUILayout.ExpandWidth(true));
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition);
            EditorGUI.DrawRect(rect, selected ? Accent : hover ? Border : Panel);
            EditorGUI.DrawRect(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f), hover ? PanelHover : Panel);
            var dot = new Rect(rect.x + 10f, rect.y + 9f, 12f, 12f);
            EditorGUI.DrawRect(dot, selected ? Accent : Border);
            if (!selected)
                EditorGUI.DrawRect(new Rect(dot.x + 2f, dot.y + 2f, 8f, 8f), Panel);
            GUI.Label(new Rect(rect.x + 30f, rect.y + 5f, rect.width - 40f, 20f), label, rowTitle);
            GUI.Label(new Rect(rect.x + 30f, rect.y + 24f, rect.width - 40f, height - 26f), detail, rowBody);
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            GUILayout.Space(4f);
            if (e.type == EventType.MouseDown && e.button == 0 && hover)
            {
                e.Use();
                return true;
            }
            return false;
        }

        private bool BigButton(string label, float width)
        {
            var rect = GUILayoutUtility.GetRect(width, 32f, GUILayout.Width(width));
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition) && GUI.enabled;
            EditorGUI.DrawRect(rect, GUI.enabled ? (hover ? Accent : AccentDim) : Border);
            buttonText.normal.textColor = hover ? AccentText : TitleText;
            GUI.Label(rect, label, buttonText);
            if (GUI.enabled)
                EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            if (GUI.enabled && e.type == EventType.MouseDown && e.button == 0 && hover)
            {
                e.Use();
                return true;
            }
            return false;
        }

        private bool SmallButton(string label)
        {
            var size = rowBody.CalcSize(new GUIContent(label));
            var rect = GUILayoutUtility.GetRect(size.x + 20f, 28f, GUILayout.Width(size.x + 20f));
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition);
            EditorGUI.DrawRect(rect, hover ? AccentDim : Border);
            EditorGUI.DrawRect(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f), hover ? PanelHover : Background);
            GUI.Label(rect, label, new GUIStyle(rowBody) { alignment = TextAnchor.MiddleCenter });
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            if (e.type == EventType.MouseDown && e.button == 0 && hover)
            {
                e.Use();
                return true;
            }
            return false;
        }

        private void Styles()
        {
            if (titleStyle != null)
                return;
            titleStyle = new GUIStyle(EditorStyles.boldLabel) { fontSize = 17, normal = { textColor = TitleText } };
            body = new GUIStyle(EditorStyles.label) { fontSize = 12, wordWrap = true, normal = { textColor = BodyText } };
            dim = new GUIStyle(EditorStyles.label) { fontSize = 11, wordWrap = true, normal = { textColor = DimText } };
            section = new GUIStyle(EditorStyles.boldLabel) { fontSize = 12, normal = { textColor = Accent } };
            rowTitle = new GUIStyle(EditorStyles.boldLabel) { fontSize = 12, normal = { textColor = TitleText } };
            rowBody = new GUIStyle(EditorStyles.label) { fontSize = 11, wordWrap = true, normal = { textColor = BodyText } };
            buttonText = new GUIStyle(EditorStyles.boldLabel) { fontSize = 13, alignment = TextAnchor.MiddleCenter };
            field = new GUIStyle(EditorStyles.textField) { fontSize = 12, padding = new RectOffset(6, 6, 3, 3) };
        }
    }
}
#endif
