using Microsoft.Maui.Controls;
using TodoList.Maui.Models;
using TodoList.Maui.Services;

namespace TodoList.Maui.Views
{
    public partial class MainPage : ContentPage
    {
        private readonly IHotKeySettingsService _settingsService;
#if WINDOWS
        private Platforms.Windows.WindowsKeyboardHandler? _keyboardHandler;
#endif

        public MainPage()
        {
            InitializeComponent();
            _settingsService = new HotKeySettingsService();
            SetupWebViewCommunication();
            SetupKeyboardHandler();
        }

        public const string Version = "1.0.0";

        private void SetupKeyboardHandler()
        {
#if WINDOWS
            _keyboardHandler = new Platforms.Windows.WindowsKeyboardHandler();
            _keyboardHandler.EscKeyPressed += OnEscKeyPressed;
            _keyboardHandler.Start();
#endif
        }

        private void OnEscKeyPressed(object? sender, EventArgs e)
        {
            var window = Application.Current?.Windows.FirstOrDefault();
            if (window != null)
            {
#if WINDOWS
                var windowService = new Platforms.Windows.WindowsWindowService();
                windowService.MinimizeWindow(window);
#endif
            }
        }

        private void SetupWebViewCommunication()
        {
            MainWebView.Navigated += async (s, e) =>
            {
                await MainWebView.EvaluateJavaScriptAsync(@"
                    window.mauiInterop = {
                        onHotKeyConfigUpdated: null,
                        openHotKeySettings: function(config) {
                            const event = new CustomEvent('openHotKeySettings', { detail: config });
                            window.dispatchEvent(event);
                        },
                        updateHotKeyConfig: function(modifiers, key, isEnabled) {
                            const event = new CustomEvent('updateHotKeyConfig', { 
                                detail: { modifiers, key, isEnabled }
                            });
                            window.dispatchEvent(event);
                        }
                    };
                    
                    window.addEventListener('hotKeyConfigChanged', function(e) {
                        if (window.mauiInterop.onHotKeyConfigUpdated) {
                            window.mauiInterop.onHotKeyConfigUpdated(e.detail);
                        }
                    });
                ");
            };

            // MainWebView.WebMessageReceived += async (s, e) =>
            // {
            //     try
            //     {
            //         var message = e.Message;
            //         if (message.StartsWith("HOTKEY_CONFIG:"))
            //         {
            //             var configJson = message.Substring("HOTKEY_CONFIG:".Length);
            //             var config = System.Text.Json.JsonSerializer.Deserialize<HotKeyConfig>(configJson);
            //             if (config != null)
            //             {
            //                 _settingsService.SaveConfig(config);
            //             }
            //         }
            //     }
            //     catch (Exception ex)
            //     {
            //         System.Diagnostics.Debug.WriteLine($"Error processing web message: {ex.Message}");
            //     }
            // };
        }

        private async void OnHotKeySettingsClicked(object sender, EventArgs e)
        {
            var config = _settingsService.GetConfig();
            var configJson = System.Text.Json.JsonSerializer.Serialize(config);
            await MainWebView.EvaluateJavaScriptAsync($"window.mauiInterop.openHotKeySettings({configJson});");
        }
    }
}