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

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

        public MainPage()
        {
            InitializeComponent();
            _appSettings = Microsoft.Maui.Controls.Application.Current?.Handler?.MauiContext?.Services
                .GetService<AppSettings>() ?? new AppSettings();

            SetupWebViewSource();
            SetupWebViewCommunication();
            SetupKeyboardHandler();
        }


        private void SetupWebViewSource()
        {


            if (_appSettings.WebServer.IsUsingStatic)
            {
                var webServer = Microsoft.Maui.Controls.Application.Current?.Handler?.MauiContext?.Services
                    .GetService<IEmbeddedWebServerService>();
                if (webServer is { IsRunning: true })
                {
                    MainWebView.Source = webServer.BaseUrl;
                }
            }
            else
            {
                MainWebView.Source = _appSettings.WebServer.ForEndUrl;
            }
        }

        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 = Microsoft.Maui.Controls.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) =>
            {
#if !DEBUG
                await MainWebView.EvaluateJavaScriptAsync($"window.__API_BASE_URL__ = '{_appSettings.WebServer.HostUrl}/api';");
#endif

                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);
                        }
                    });
                ");
            };
        }
    }
}
