using Microsoft.Maui.Controls;
using Hua.Todo.Maui.Services;
using System.Runtime.InteropServices;
using Windowing = Microsoft.UI.Windowing;
using WinUiWindow = Microsoft.UI.Xaml.Window;
using WinRT.Interop;

namespace Hua.Todo.Maui;

/// <summary>
/// Windows 平台特定的 App 逻辑（分部类）。
/// 该文件仅在 Windows 目标框架下参与编译，用于承载窗口句柄相关能力与 WinUI API 调用。
/// </summary>
public partial class App
{
	/// <summary>
	/// 初始化 Windows 平台特定设置。
	/// 例如：自定义 MAUI TitleBar（不是 WinUI TitleBar）。
	/// </summary>
	partial void InitializePlatform()
	{
		if (_mainWindow != null)
		{
			_mainWindow.TitleBar = CreateWindowTitleBar();
		}
	}

	/// <summary>
	/// Windows 平台窗口创建后的处理。
	/// 该回调发生在 Window Created 之后，但依然可能需要等待 Handler/PlatformView 就绪，因此使用 UI 线程调度。
	/// </summary>
	/// <param name="window">MAUI Window。</param>
	partial void OnPlatformWindowCreated(Window window)
	{
		MainThread.BeginInvokeOnMainThread(() =>
		{
			if (window.Handler?.PlatformView is WinUiWindow platformWindow)
			{
				// 关闭按钮行为：拦截关闭并隐藏到系统托盘，避免进程退出。
				// 注意：该逻辑与系统托盘功能配套，托盘菜单提供“退出应用”入口。
				platformWindow.AppWindow.Closing += (sender, args) =>
				{
					args.Cancel = true;
					new Hua.Todo.Maui.Platforms.Windows.WindowsWindowService().HideWindow(window);
				};

				CenterMainWindow(platformWindow);
				ConfigureWindowsTitleBar(platformWindow);
			}
		});
	}

	/// <summary>
	/// 检查 Windows 平台视图是否准备就绪
	/// </summary>
	/// <param name="window">MAUI Window。</param>
	/// <returns>当 PlatformView 是 WinUI Window 时返回 true。</returns>
	private partial bool IsPlatformViewReady(Window window)
	{
		return window.Handler?.PlatformView is WinUiWindow;
	}

	/// <summary>
	/// 在 Windows 平台上显示主窗口
	/// </summary>
	/// <param name="window">MAUI Window。</param>
	/// <returns>已恢复并激活窗口返回 true；否则返回 false。</returns>
	private partial bool PlatformShowMainWindow(Window window)
	{
		if (window.Handler != null)
		{
			new Hua.Todo.Maui.Platforms.Windows.WindowsWindowService().RestoreWindow(window);
			var platformWindow = window.Handler.PlatformView as WinUiWindow;
			platformWindow?.Activate();
			return true;
		}
		return false;
	}

	/// <summary>
	/// 配置 Windows 标题栏（WinUI AppWindow.TitleBar）。
	/// 用于设置窗口标题、图标以及标题栏按钮样式等。
	/// </summary>
	/// <param name="platformWindow">WinUI Window。</param>
	private void ConfigureWindowsTitleBar(WinUiWindow platformWindow)
	{
		var title = AppMetadata.GetWindowTitle();

		platformWindow.Title = title;
		if (_mainWindow != null)
		{
			_mainWindow.Title = title;
		}

		var appWindow = platformWindow.AppWindow;
		if (appWindow != null)
		{
			appWindow.Title = title;

			var hWnd = WindowNative.GetWindowHandle(platformWindow);
			if (hWnd != IntPtr.Zero)
			{
				SetWindowText(hWnd, title);
			}

			var iconPath = Path.Combine(AppContext.BaseDirectory, "icon.ico");
			if (File.Exists(iconPath))
			{
				appWindow.SetIcon(iconPath);
			}

			var titleBar = appWindow.TitleBar;
			titleBar.IconShowOptions = Windowing.IconShowOptions.ShowIconAndSystemMenu;

			titleBar.BackgroundColor = Microsoft.UI.Colors.Transparent;
			titleBar.InactiveBackgroundColor = Microsoft.UI.Colors.Transparent;
			titleBar.ButtonBackgroundColor = Microsoft.UI.Colors.Transparent;
			titleBar.ButtonInactiveBackgroundColor = Microsoft.UI.Colors.Transparent;
			titleBar.ButtonHoverBackgroundColor = Microsoft.UI.Colors.Transparent;
			titleBar.ButtonPressedBackgroundColor = Microsoft.UI.Colors.Transparent;
			titleBar.ButtonForegroundColor = Microsoft.UI.Colors.Black;
			titleBar.ButtonInactiveForegroundColor = Microsoft.UI.Colors.Black;
			titleBar.ButtonHoverForegroundColor = Microsoft.UI.Colors.Black;
			titleBar.ButtonPressedForegroundColor = Microsoft.UI.Colors.Black;
		}
	}

	[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "SetWindowTextW")]
	private static extern bool SetWindowText(IntPtr hWnd, string lpString);

	/// <summary>
	/// 创建 MAUI 自定义标题栏内容。
	/// 用于在窗口标题栏区域展示应用图标与版本信息。
	/// </summary>
	private static TitleBar CreateWindowTitleBar()
	{
		return new TitleBar
		{
			BackgroundColor = Microsoft.Maui.Graphics.Color.FromArgb("#F5F5F5"),
			Icon = string.Empty,
			Title = string.Empty,
			ForegroundColor = Microsoft.Maui.Graphics.Color.FromArgb("#333333"),
			LeadingContent = new HorizontalStackLayout
			{
				Spacing = 4,
				Padding = new Microsoft.Maui.Thickness(10, 0, 0, 0),
				VerticalOptions = LayoutOptions.Center,
				Children =
				{
					new Image
					{
						Source = "icon.jpg",
						WidthRequest = 22,
						HeightRequest = 22,
						VerticalOptions = LayoutOptions.Center
					},
					new Label
					{
						Text = AppMetadata.GetTitleBarVersionText(),
						FontFamily = "Microsoft YaHei UI",
						TextColor = Microsoft.Maui.Graphics.Color.FromArgb("#333333"),
						VerticalTextAlignment = Microsoft.Maui.TextAlignment.Center,
						VerticalOptions = LayoutOptions.Center,
						FontSize = 14
					}
				}
			}
		};
	}

	/// <summary>
	/// 居中显示主窗口
	/// </summary>
	/// <param name="platformWindow">WinUI Window。</param>
	private void CenterMainWindow(WinUiWindow platformWindow)
	{
		if (_isWindowCentered) return;

		var appWindow = platformWindow.AppWindow;
		if (appWindow == null) return;

		var displayArea = Windowing.DisplayArea.GetFromWindowId(
			appWindow.Id,
			Windowing.DisplayAreaFallback.Primary);

		var workArea = displayArea.WorkArea;

		var windowWidthPx = appWindow.Size.Width;
		var windowHeightPx = appWindow.Size.Height;

		if (windowWidthPx <= 0 || windowHeightPx <= 0)
		{
			var scale = platformWindow.Content?.XamlRoot?.RasterizationScale ?? 1.0;
			windowWidthPx = windowWidthPx <= 0 ? (int)Math.Round((_mainWindow?.Width ?? 450) * scale) : windowWidthPx;
			windowHeightPx = windowHeightPx <= 0 ? (int)Math.Round((_mainWindow?.Height ?? 640) * scale) : windowHeightPx;
		}

		if (windowWidthPx <= 0 || windowHeightPx <= 0) return;

		var x = workArea.X + (workArea.Width - windowWidthPx) / 2;
		var y = workArea.Y + (workArea.Height - windowHeightPx) / 2;

		if (windowWidthPx >= workArea.Width) x = workArea.X;
		if (windowHeightPx >= workArea.Height) y = workArea.Y;

		x = Math.Max(workArea.X, Math.Min(x, workArea.X + workArea.Width - windowWidthPx));
		y = Math.Max(workArea.Y, Math.Min(y, workArea.Y + workArea.Height - windowHeightPx));

		appWindow.Move(new Windows.Graphics.PointInt32(x, y));
		_isWindowCentered = true;
	}
}
