using Microsoft.UI;
using Microsoft.UI.Text;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Windows.Graphics;
using WinRT.Interop;
using YMhut.Box.Core.App;
using YMhut.Box.Core.Logging;
using YMhut.Box.Core.Settings;
using YMhut.Box.WinUI.Services;

namespace YMhut.Box.WinUI.Views;

public sealed class MediaPlayerLauncherPage : Page
{
    private readonly ILogService _logService = AppServices.GetRequiredService<ILogService>();
    private readonly AppPaths _paths = AppServices.GetRequiredService<AppPaths>();
    private readonly IIndependentWindowHostLauncher _windowHostLauncher = AppServices.GetRequiredService<IIndependentWindowHostLauncher>();
    private readonly TextBlock _stateText = ModernUi.Text(AppLocalizer.T("准备打开独立媒体播放器窗口。", "Ready to open the standalone media player window."), 14, foreground: ModernUi.TextSecondary);
    private bool _opened;

    public MediaPlayerLauncherPage()
    {
        Background = ModernUi.AppBackground;
        Content = BuildContent();
    }

    private UIElement BuildContent()
    {
        var openButton = ModernUi.PillButton(AppLocalizer.T("打开新的媒体播放器窗口", "Open a new media player window"), "\uE8D6", () => OpenPlayerWindow(auto: false), primary: true);

        var card = ModernUi.Card(new StackPanel
        {
            Spacing = 16,
            Children =
            {
                ModernUi.IconTile("\uE8D6", 56, ModernUi.AccentSoft, ModernUi.Accent, 24),
                ModernUi.Text(AppLocalizer.T("媒体播放器", "Media Player"), 24, FontWeights.SemiBold),
                ModernUi.Text(AppLocalizer.T("播放器会在独立进程窗口中运行，使用 Windows Media Foundation 播放图片、音频和视频；主窗口保留最近访问和操作日志。", "The player runs in a standalone process window, uses Windows Media Foundation for images, audio, and video, and keeps recent visits and action logs in the main window."), 14, foreground: ModernUi.TextSecondary, maxLines: 3),
                _stateText,
                openButton
            }
        }, new Thickness(24), radius: 8);

        return new Grid
        {
            Padding = new Thickness(0, 0, 24, 0),
            Children = { card }
        };
    }

    private async void OpenPlayerWindow(bool auto)
    {
        if (auto && _opened)
        {
            return;
        }

        _opened = true;
        await _windowHostLauncher.LaunchAsync(IndependentWindowHostOptions.Media(
            AppLocalizer.T("媒体播放器", "Media Player"),
            _paths));
        _stateText.Text = AppLocalizer.T($"媒体播放器窗口已打开：{DateTime.Now:HH:mm:ss}", $"Media player window opened: {DateTime.Now:HH:mm:ss}");
        ToastService.Show(AppLocalizer.T("媒体播放器窗口已打开", "Media player window opened"), ToastKind.Success);
        _ = _logService.WriteAsync("Information", "media_player", auto ? "自动打开媒体播放器独立进程窗口" : "手动打开媒体播放器独立进程窗口");
    }
}

public sealed class MediaPlayerWindow : Window
{
    private readonly MediaPlayerPage _page;
    private readonly TitleBarDragRegionHelper _titleBarHelper;
    private readonly WindowMovePerformanceHelper _movePerformanceHelper;
    private readonly ISettingsService _settingsService = AppServices.GetRequiredService<ISettingsService>();
    private readonly IUiPerformanceCoordinator _uiPerformanceCoordinator = AppServices.GetRequiredService<IUiPerformanceCoordinator>();
    private IDisposable? _moveLightModeScope;

    public MediaPlayerWindow()
    {
        Title = AppLocalizer.T("YMhut Box · 媒体播放器", "YMhut Box · Media Player");
        _page = new MediaPlayerPage(this, MediaPlayerShellMode.Standalone);
        var shell = new IndependentWindowShell(
            AppLocalizer.T("媒体播放器", "Media player"),
            "\uE8D6",
            AppLocalizer.T("媒体播放器", "Media Player"),
            IndependentWindowShellMode.Tool);
        shell.SetContent(_page);
        shell.CommandSubmitted += (_, _) => _page.OpenFilesFromShell();
        shell.BackButton.Click += (_, _) => _page.ShowPreviousFromShell();
        shell.ForwardButton.Click += (_, _) => _page.ShowNextFromShell();
        shell.StopButton.Click += (_, _) => _page.StopFromShell();
        shell.ExtensionButton.Click += (_, _) => _page.OpenFilesFromShell();
        shell.MenuButton.Click += (_, _) => _page.ClearPlaylistFromShell();
        shell.SetButtonToolTip(shell.ExtensionButton, AppLocalizer.T("打开媒体", "Open media"));
        shell.SetButtonToolTip(shell.MenuButton, AppLocalizer.T("清空列表", "Clear playlist"));
        Content = shell.Root;
        WindowIconService.ApplyAppIcon(this);
        _titleBarHelper = new TitleBarDragRegionHelper(this, shell.TitleBar, shell.PassthroughElements);
        _movePerformanceHelper = WindowMovePerformanceHelper.Attach(
            this,
            () => _settingsService.Current.WindowBackdrop,
            active =>
            {
                if (active)
                {
                    _moveLightModeScope ??= _uiPerformanceCoordinator.EnterLightMode("media-window-move");
                }
                else
                {
                    _moveLightModeScope?.Dispose();
                    _moveLightModeScope = null;
                }
            });
        Closed += (_, _) => _moveLightModeScope?.Dispose();
        ConfigureWindowSize();
    }

    private void ConfigureWindowSize()
    {
        var hwnd = WindowNative.GetWindowHandle(this);
        var id = Win32Interop.GetWindowIdFromWindow(hwnd);
        var appWindow = AppWindow.GetFromWindowId(id);
        appWindow.Resize(new SizeInt32(1240, 780));
    }
}
