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;
        private readonly IEmbeddedWebServerService? _webServer;
#if WINDOWS
        private Platforms.Windows.WindowsKeyboardHandler? _keyboardHandler;
#endif

        public MainPage(AppSettings appSettings, IEmbeddedWebServerService webServer)
        {
            InitializeComponent();
            _appSettings = appSettings;
            _webServer = webServer;

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


        private void SetupWebViewSource()
        {
            if (_appSettings.WebServer.IsUsingStatic)
            {
                if (_webServer != null)
                {
                    MainWebView.Source = _webServer.BaseUrl;
                    return;
                }
            }

            MainWebView.Source = NormalizeUrl(_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
                if (e.Result != WebNavigationResult.Success)
                {
                    await DisplayAlertAsync("加载失败", $"{e.Url}\n{e.Result}", "OK");
                }
#endif

                if (_webServer is { IsRunning: true })
                {
                    var apiBase = $"{_webServer.BaseUrl.TrimEnd('/')}/api";
                    await MainWebView.EvaluateJavaScriptAsync($"window.__API_BASE_URL__ = '{apiBase}';");
                }

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

        private static string NormalizeUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url)) return url;
            if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) return url;

            var host = uri.Host;
            if (host != "localhost" && host != "127.0.0.1") return url;

            if (DeviceInfo.Platform == DevicePlatform.Android && DeviceInfo.DeviceType == DeviceType.Virtual)
            {
                var builder = new UriBuilder(uri) { Host = "10.0.2.2" };
                return builder.Uri.ToString();
            }

            return url;
        }
    }
}
