using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Overlays;
using UnityEditor.Toolbars;
using UnityEngine;
using UnityEngine.UIElements;

namespace UnityAssistant
{
    [Overlay(typeof(SceneView), OverlayId, "Gumo", true)]
    [Icon("d_console.infoicon")]
    public class BridgeOverlay : ToolbarOverlay
    {
        public const string OverlayId = "UnityAssistant/Bridge";

        private BridgeOverlay() : base(BridgeStatusButton.Id) { }
    }

    [EditorToolbarElement(Id, typeof(SceneView))]
    public class BridgeStatusButton : EditorToolbarButton
    {
        public const string Id = "UnityAssistant/BridgeStatus";

        private static readonly Color AccentGreen = new Color(0.604f, 0.804f, 0.196f);
        private static readonly Color RedDim = new Color(0.78f, 0.28f, 0.28f);

        private readonly VisualElement _dot;
        private readonly Label _label;

        public BridgeStatusButton()
        {
            name = "BridgeStatusButton";
            tooltip = "Gumo Bridge — left-click for status, right-click for menu";

            style.flexDirection = FlexDirection.Row;
            style.alignItems = Align.Center;
            style.paddingLeft = 6;
            style.paddingRight = 8;

            _dot = new VisualElement();
            _dot.style.width = 8;
            _dot.style.height = 8;
            _dot.style.marginRight = 6;
            _dot.style.borderTopLeftRadius = 4;
            _dot.style.borderTopRightRadius = 4;
            _dot.style.borderBottomLeftRadius = 4;
            _dot.style.borderBottomRightRadius = 4;
            Add(_dot);

            _label = new Label("AI");
            _label.style.unityFontStyleAndWeight = FontStyle.Bold;
            _label.style.fontSize = 11;
            Add(_label);

            clicked += BridgeStatusWindow.Open;
            this.AddManipulator(new ContextualMenuManipulator(BuildMenu));

            BridgeServer.OnStateChanged += Refresh;
            RegisterCallback<AttachToPanelEvent>(_ => Refresh());
            RegisterCallback<DetachFromPanelEvent>(_ => BridgeServer.OnStateChanged -= Refresh);
            EditorApplication.update += Tick;
        }

        ~BridgeStatusButton()
        {
            EditorApplication.update -= Tick;
            BridgeServer.OnStateChanged -= Refresh;
        }

        private double _lastTick;
        private void Tick()
        {
            if (EditorApplication.timeSinceStartup - _lastTick > 2.0)
            {
                _lastTick = EditorApplication.timeSinceStartup;
                Refresh();
            }
        }

        private void Refresh()
        {
            bool running = BridgeServer.IsRunning;
            _dot.style.backgroundColor = running ? AccentGreen : RedDim;
            _label.text = running ? "AI" : "AI (off)";
            _label.style.color = running ? AccentGreen : new Color(0.6f, 0.6f, 0.65f);
        }

        private void BuildMenu(ContextualMenuPopulateEvent evt)
        {
            if (BridgeServer.IsRunning)
            {
                evt.menu.AppendAction("Stop Bridge", _ => BridgeServer.Stop());
                evt.menu.AppendAction("Restart Bridge", _ => BridgeServer.Restart());
            }
            else
            {
                evt.menu.AppendAction("Start Bridge", _ => BridgeServer.Start());
            }
            evt.menu.AppendSeparator();
            evt.menu.AppendAction("Open Status…", _ => BridgeStatusWindow.Open());
            evt.menu.AppendAction("Reindex Project", _ =>
                IndexerTools.IndexProject(new Dictionary<string, object> { ["force"] = true }));
            evt.menu.AppendSeparator();
            evt.menu.AppendAction("Auto-start on Editor Launch",
                _ => BridgePrefs.AutoStart = !BridgePrefs.AutoStart,
                _ => BridgePrefs.AutoStart ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal);
        }
    }
}
