using System;
using UnityEditor;
using UnityEngine;

namespace UnityAssistant
{
    public class BridgeStatusWindow : EditorWindow
    {
        private static readonly Color AccentGreen = new Color(0.604f, 0.804f, 0.196f); // #9ACD32
        private static readonly Color BgDark = new Color(0.055f, 0.055f, 0.063f);
        private static readonly Color BgPanel = new Color(0.082f, 0.082f, 0.094f);
        private static readonly Color TextDim = new Color(0.72f, 0.72f, 0.76f);

        public static void Open()
        {
            var w = GetWindow<BridgeStatusWindow>(false, "Gumo", true);
            w.minSize = new Vector2(360, 240);
            w.Show();
        }

        private void OnEnable()
        {
            BridgeServer.OnStateChanged += Repaint;
            EditorApplication.update += OnUpdate;
        }

        private void OnDisable()
        {
            BridgeServer.OnStateChanged -= Repaint;
            EditorApplication.update -= OnUpdate;
        }

        private double _lastRepaint;
        private void OnUpdate()
        {
            if (EditorApplication.timeSinceStartup - _lastRepaint > 1.0)
            {
                _lastRepaint = EditorApplication.timeSinceStartup;
                Repaint();
            }
        }

        private void OnGUI()
        {
            EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), BgDark);

            GUILayout.Space(14);

            // Header with status dot
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(16);
                var dotRect = GUILayoutUtility.GetRect(12, 12, GUILayout.Width(12), GUILayout.Height(12));
                dotRect.y += 4;
                EditorGUI.DrawRect(dotRect, BridgeServer.IsRunning ? AccentGreen : new Color(0.6f, 0.28f, 0.28f));

                GUILayout.Space(10);
                var titleStyle = new GUIStyle(EditorStyles.boldLabel) { fontSize = 16, normal = { textColor = Color.white } };
                GUILayout.Label("Gumo Bridge", titleStyle);
                GUILayout.FlexibleSpace();
                GUILayout.Space(16);
            }

            GUILayout.Space(10);
            DrawSeparator();
            GUILayout.Space(12);

            // Status fields
            DrawField("Status", BridgeServer.IsRunning ? "Listening" : "Stopped",
                BridgeServer.IsRunning ? AccentGreen : TextDim);
            DrawField("URL", $"http://127.0.0.1:{BridgeServer.PortNumber}/", TextDim);
            DrawField("Requests", BridgeServer.RequestCount.ToString(), TextDim);
            if (BridgeServer.IsRunning)
            {
                var uptime = DateTime.Now - BridgeServer.StartedAt;
                DrawField("Uptime", FormatUptime(uptime), TextDim);
            }
            if (!string.IsNullOrEmpty(BridgeServer.LastError))
                DrawField("Last error", BridgeServer.LastError, new Color(0.9f, 0.3f, 0.3f));

            GUILayout.Space(14);
            DrawSeparator();
            GUILayout.Space(12);

            // Buttons
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(12);
                if (BridgeServer.IsRunning)
                {
                    if (AccentButton("■ Stop", false)) BridgeServer.Stop();
                    GUILayout.Space(6);
                    if (AccentButton("↻ Restart", false)) BridgeServer.Restart();
                }
                else
                {
                    if (AccentButton("▶ Start Bridge", true)) BridgeServer.Start();
                }
                GUILayout.FlexibleSpace();
                if (PlainButton("Copy URL"))
                {
                    EditorGUIUtility.systemCopyBuffer = $"http://127.0.0.1:{BridgeServer.PortNumber}/";
                }
                GUILayout.Space(12);
            }

            GUILayout.Space(10);
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(12);
                bool autoStart = BridgePrefs.AutoStart;
                bool next = EditorGUILayout.ToggleLeft("Auto-start when Editor opens", autoStart, GUILayout.Width(220));
                if (next != autoStart) BridgePrefs.AutoStart = next;
                GUILayout.FlexibleSpace();
                GUILayout.Space(12);
            }

            GUILayout.Space(10);
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(12);
                if (PlainButton("Reindex Project"))
                    IndexerTools.IndexProject(new System.Collections.Generic.Dictionary<string, object> { ["force"] = true });
                GUILayout.Space(12);
            }
        }

        private void DrawField(string label, string value, Color valueColor)
        {
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(16);
                var labelStyle = new GUIStyle(EditorStyles.label)
                { fontSize = 11, normal = { textColor = new Color(0.5f, 0.5f, 0.55f) } };
                GUILayout.Label(label.ToUpper(), labelStyle, GUILayout.Width(80));
                var valStyle = new GUIStyle(EditorStyles.label) { normal = { textColor = valueColor } };
                GUILayout.Label(value, valStyle);
                GUILayout.FlexibleSpace();
                GUILayout.Space(16);
            }
            GUILayout.Space(4);
        }

        private void DrawSeparator()
        {
            var r = GUILayoutUtility.GetRect(1, 1, GUILayout.ExpandWidth(true));
            r.x += 12; r.width -= 24;
            EditorGUI.DrawRect(r, new Color(0.18f, 0.18f, 0.21f));
        }

        private bool AccentButton(string label, bool primary)
        {
            var c = GUI.backgroundColor;
            GUI.backgroundColor = primary ? AccentGreen : new Color(0.16f, 0.16f, 0.19f);
            var style = new GUIStyle(GUI.skin.button) { fontSize = 12, fixedHeight = 26, padding = new RectOffset(14, 14, 4, 4) };
            if (primary) style.normal.textColor = Color.black;
            bool clicked = GUILayout.Button(label, style);
            GUI.backgroundColor = c;
            return clicked;
        }

        private bool PlainButton(string label)
        {
            var style = new GUIStyle(GUI.skin.button) { fontSize = 11, fixedHeight = 22, padding = new RectOffset(10, 10, 2, 2) };
            return GUILayout.Button(label, style);
        }

        private static string FormatUptime(TimeSpan t)
        {
            if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m";
            if (t.TotalMinutes >= 1) return $"{t.Minutes}m {t.Seconds}s";
            return $"{t.Seconds}s";
        }
    }
}
