#if WINDOWS
using System.Runtime.InteropServices;
using Microsoft.UI.Input;
using Microsoft.UI.Xaml.Input;
using WinRT.Interop;
using MauiWindow = Microsoft.Maui.Controls.Window;

namespace TodoList.Maui.Services.Platforms
{
    /// <summary>
    /// Windows 平台全局热键服务实现类
    /// 使用 Windows API 实现全局热键功能
    /// </summary>
    public class WindowsGlobalHotKeyService : IGlobalHotKeyService
    {
        private const int HOTKEY_ID = 9000;
        private const int WM_HOTKEY = 0x0312;

        public const uint MOD_ALT = 0x0001;
        public const uint MOD_CONTROL = 0x0002;
        public const uint MOD_SHIFT = 0x0004;
        public const uint MOD_WIN = 0x0008;

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        private IntPtr _windowHandle;
        private MauiWindow? _window;
        private Action? _callback;
        private bool _isRegistered;
        private uint _currentModifiers;
        private uint _currentKey;
        private IntPtr _windowHook;

        /// <summary>
        /// Windows 平台支持全局热键
        /// </summary>
        public bool IsSupported => true;

        /// <summary>
        /// 注册全局热键
        /// </summary>
        public void RegisterHotKey(string modifiers, string key, Action callback)
        {
            if (_window == null)
            {
                _window = Application.Current?.Windows.FirstOrDefault();
                if (_window == null) return;

                var nativeWindow = WindowNative.GetWindowHandle(_window);
                _windowHandle = nativeWindow;
            }

            _callback = callback;
            _currentModifiers = ParseModifiers(modifiers);
            _currentKey = ParseKey(key);

            if (_isRegistered)
            {
                UnregisterHotKey();
            }

            if (RegisterHotKey(_windowHandle, HOTKEY_ID, _currentModifiers, _currentKey))
            {
                _isRegistered = true;
                SetupWindowHook();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Failed to register hotkey");
            }
        }

        /// <summary>
        /// 注销全局热键
        /// </summary>
        public void UnregisterHotKey()
        {
            if (_isRegistered)
            {
                if (_windowHook != IntPtr.Zero)
                {
                    UnhookWindowsHookEx(_windowHook);
                    _windowHook = IntPtr.Zero;
                }
                UnregisterHotKey(_windowHandle, HOTKEY_ID);
                _isRegistered = false;
            }
        }

        /// <summary>
        /// 更新热键配置
        /// </summary>
        public void UpdateHotKey(string modifiers, string key)
        {
            if (_callback != null)
            {
                RegisterHotKey(modifiers, key, _callback);
            }
        }

        /// <summary>
        /// 设置窗口钩子以监听热键消息
        /// </summary>
        private void SetupWindowHook()
        {
            var moduleHandle = GetModuleHandle(string.Empty);
            _windowHook = SetWindowsHookEx(WH_GETMESSAGE, HotKeyHookProc, moduleHandle, 0);
        }

        /// <summary>
        /// 热键钩子回调函数
        /// </summary>
        private IntPtr HotKeyHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                var msg = Marshal.PtrToStructure<MSG>(lParam);
                if (msg.message == WM_HOTKEY && msg.wParam == (IntPtr)HOTKEY_ID)
                {
                    _callback?.Invoke();
                }
            }
            return CallNextHookEx(_windowHook, nCode, wParam, lParam);
        }

        /// <summary>
        /// 解析修饰键字符串
        /// </summary>
        private uint ParseModifiers(string modifiers)
        {
            uint mod = 0;
            if (string.IsNullOrEmpty(modifiers)) return mod;

            var parts = modifiers.Split(',');
            foreach (var part in parts)
            {
                var p = part.Trim();
                if (p.Equals("Control", StringComparison.OrdinalIgnoreCase)) mod |= MOD_CONTROL;
                if (p.Equals("Alt", StringComparison.OrdinalIgnoreCase)) mod |= MOD_ALT;
                if (p.Equals("Shift", StringComparison.OrdinalIgnoreCase)) mod |= MOD_SHIFT;
                if (p.Equals("Windows", StringComparison.OrdinalIgnoreCase)) mod |= MOD_WIN;
            }
            return mod;
        }

        /// <summary>
        /// 解析主键
        /// </summary>
        private uint ParseKey(string key)
        {
            if (key.Length == 1)
            {
                char c = char.ToUpper(key[0]);
                if (c >= 'A' && c <= 'Z') return (uint)c;
                if (c >= '0' && c <= '9') return (uint)c;
            }
            return 0x58; // Default 'X'
        }

        [DllImport("user32.dll")]
        private static extern IntPtr SetWindowsHookEx(int idHook, HotKeyHookProcDelegate lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll")]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll")]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        private delegate IntPtr HotKeyHookProcDelegate(int nCode, IntPtr wParam, IntPtr lParam);

        [StructLayout(LayoutKind.Sequential)]
        private struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public IntPtr wParam;
            public IntPtr lParam;
            public uint time;
            public POINT pt;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            public int x;
            public int y;
        }

        private const int WH_GETMESSAGE = 3;
    }
}
#endif