#if WINDOWS
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Microsoft.UI.Xaml;
using WinRT.Interop;
using TodoList.Maui.Services;

namespace TodoList.Maui.Services.Platforms
{
    public class WindowsSystemTrayService : ISystemTrayService, IDisposable
    {
        private NotifyIcon? _notifyIcon;
        private Microsoft.Maui.Controls.Window? _window;
        private Action? _onShowWindow;
        private Action? _onExit;
        private bool _disposed;

        public void Initialize(Microsoft.Maui.Controls.Window window, Action onShowWindow, Action onExit)
        {
            _window = window;
            _onShowWindow = onShowWindow;
            _onExit = onExit;

            _notifyIcon = new NotifyIcon();
            _notifyIcon.Icon = GetAppIcon();
            _notifyIcon.Text = GetNotifyIconText();
            _notifyIcon.Visible = true;

            _notifyIcon.DoubleClick += (s, e) => _onShowWindow?.Invoke();

            var contextMenu = new ContextMenuStrip();
            contextMenu.Items.Add("打开主界面", null, (s, e) => _onShowWindow?.Invoke());
            contextMenu.Items.Add("退出", null, (s, e) => _onExit?.Invoke());
            _notifyIcon.ContextMenuStrip = contextMenu;
        }

        public void ShowBalloonTip(string title, string message)
        {
            _notifyIcon?.ShowBalloonTip(3000, title, message, ToolTipIcon.Info);
        }

        public void Dispose()
        {
            if (_disposed) return;
            _disposed = true;

            _notifyIcon?.Dispose();
            _notifyIcon = null;
        }

        private Icon GetAppIcon()
        {
            try
            {
                var assembly = System.Reflection.Assembly.GetExecutingAssembly();
                var resourceName = assembly.GetManifestResourceNames().FirstOrDefault(n => n.EndsWith("icon.ico"));
                
                if (resourceName != null)
                {
                    using (var stream = assembly.GetManifestResourceStream(resourceName))
                    {
                        if (stream != null)
                        {
                            return new Icon(stream);
                        }
                    }
                }
            }
            catch
            {
            }

            return SystemIcons.Application;
        }

        private static string GetNotifyIconText()
        {
            return AppMetadata.GetTrayTooltipText();
        }
    }
}
#endif
