using Microsoft.UI.Text;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage.Pickers;
using WinRT.Interop;
using YMhut.Box.Core.Api;
using YMhut.Box.Core.Data;
using YMhut.Box.Core.Settings;
using YMhut.Box.Core.Tools;
using YMhut.Box.WinUI.Services;

namespace YMhut.Box.WinUI.Views;

public sealed partial class ToolDetailPage : ToolPageBase
{
    private readonly Action? _goBack;
    private readonly IApiManager _apiManager = AppServices.GetRequiredService<IApiManager>();
    private readonly IReferenceDataService _referenceDataService = AppServices.GetRequiredService<IReferenceDataService>();
    private readonly ISettingsService _settingsService = AppServices.GetRequiredService<ISettingsService>();
    private readonly IToolWorkerService _workerService = AppServices.GetRequiredService<IToolWorkerService>();
    private readonly TextBox _inputBox = new()
    {
        Header = null,
        AcceptsReturn = true,
        MinHeight = 180,
        TextWrapping = TextWrapping.Wrap
    };
    private readonly TextBox _outputBox = new()
    {
        Header = "输出",
        AcceptsReturn = true,
        IsReadOnly = true,
        MinHeight = 260,
        TextWrapping = TextWrapping.Wrap
    };
    private readonly InfoBar _statusBar = new()
    {
        IsOpen = true,
        Severity = InfoBarSeverity.Informational,
        Title = "WinUI 原生执行",
        Message = "此页面使用 C#/.NET 工具执行器和统一服务层。"
    };
    private readonly ContentControl _nativeToolHost = new() { Visibility = Visibility.Collapsed };
    private readonly ScrollViewer _standardToolHost = new();
    private readonly ProgressRing _progressRing = new()
    {
        Width = 24,
        Height = 24,
        IsActive = false,
        Visibility = Visibility.Collapsed,
        VerticalAlignment = VerticalAlignment.Center
    };
    private readonly StackPanel _examplesPanel = new()
    {
        Orientation = Orientation.Horizontal,
        Spacing = 8
    };
    private readonly Button _browseButton;

    private IToolModule? _module;

    public ToolDetailPage(IToolModule module, Action? goBack = null)
    {
        _goBack = goBack;
        _module = module;
        _browseButton = ModernUi.PillButton("选择文件", "\uE8E5", BrowseInputFile);
        _browseButton.Visibility = Visibility.Collapsed;
        Background = ModernUi.AppBackground;
        Content = BuildLayout();
        SetModule(module);
    }

    public void SetModule(IToolModule module)
    {
        _module = module;
        BindModule(module);
        _ = _settingsService.RecordRecentToolAsync(module.Id);

        if (module.Id == "safe_browser")
        {
            ShowNativeTool(new SafeBrowserLauncherPage());
            return;
        }

        if (module.Id == "media_player")
        {
            ShowNativeTool(new MediaPlayerPage(shellMode: MediaPlayerShellMode.Embedded));
            return;
        }

        _standardToolHost.Visibility = Visibility.Visible;
        _nativeToolHost.Visibility = Visibility.Collapsed;
        _nativeToolHost.Content = null;
        _inputBox.PlaceholderText = BuildInputHint(module);
        _inputBox.Text = DefaultInput(module);
        _outputBox.Text = string.Empty;
        _browseButton.Visibility = RequiresFilePath(module.Id) ? Visibility.Visible : Visibility.Collapsed;
        RefreshExamples(module);
    }

    private UIElement BuildLayout()
    {
        var root = new Grid();
        root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
        root.RowDefinitions.Add(new RowDefinition());

        var header = BuildModernHeader();
        Grid.SetRow(header, 0);
        root.Children.Add(header);

        _standardToolHost.Content = BuildStandardToolPanel();
        Grid.SetRow(_standardToolHost, 1);
        root.Children.Add(_standardToolHost);

        Grid.SetRow(_nativeToolHost, 1);
        root.Children.Add(_nativeToolHost);
        return root;
    }

    private Border BuildHeader()
    {
        if (_module is null)
        {
            return ModernUi.Card(ModernUi.Text("工具详情", 24, FontWeights.SemiBold), new Thickness(20), margin: new Thickness(32, 28, 32, 12), radius: 8);
        }

        var back = ModernUi.IconButton("\uE72B", "返回工具箱", () => _goBack?.Invoke());
        var grid = new Grid { ColumnSpacing = 14 };
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.ColumnDefinitions.Add(new ColumnDefinition());
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.Children.Add(back);

        var icon = ModernUi.IconTile(_module.Metadata.IconGlyph, 48, ModernUi.AccentSoft, ModernUi.Accent, 21);
        Grid.SetColumn(icon, 1);
        grid.Children.Add(icon);

        var title = new StackPanel
        {
            Spacing = 4,
            VerticalAlignment = VerticalAlignment.Center,
            Children =
            {
                ModernUi.Text(ToolText.Name(_module), 24, FontWeights.SemiBold, maxLines: 1),
                ModernUi.Text($"{ToolText.CategoryLabel(_module.Metadata.Category)} / {(_module.Metadata.OfflineCapable ? "本地可用" : "联网工具")}", 14, foreground: ModernUi.TextSecondary),
                ModernUi.Text(ToolText.Description(_module), 14, foreground: ModernUi.TextSecondary, maxLines: 2)
            }
        };
        Grid.SetColumn(title, 2);
        grid.Children.Add(title);

        var run = ModernUi.PillButton("执行", "\uE768", RunCurrentTool, primary: true);
        Grid.SetColumn(run, 3);
        grid.Children.Add(run);
        return ModernUi.Card(grid, new Thickness(18), margin: new Thickness(32, 28, 32, 12), radius: 8);
    }

    private UIElement BuildStandardToolPanel()
    {
        var runButton = ModernUi.PillButton("执行", "\uE768", RunCurrentTool, primary: true);
        var copyButton = ModernUi.PillButton("复制输出", "\uE8C8", CopyResult);
        var clearButton = ModernUi.PillButton("清空", "\uE74D", () =>
        {
            _inputBox.Text = string.Empty;
            _outputBox.Text = string.Empty;
        });

        return new StackPanel
        {
            Padding = new Thickness(24, 0, 24, 24),
            Spacing = 16,
            Children =
            {
                _statusBar,
                _inputBox,
                _examplesPanel,
                new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, Children = { runButton, _browseButton, copyButton, clearButton, _progressRing } },
                _outputBox
            }
        };
    }

    private async void RunCurrentTool()
    {
        if (_module is null)
        {
            return;
        }

        _statusBar.Severity = InfoBarSeverity.Informational;
        _statusBar.Title = AppLocalizer.T("执行中", "Running");
        _statusBar.Message = AppLocalizer.T("正在处理当前工具。", "Processing this tool.");

        _progressRing.Visibility = Visibility.Visible;
        _progressRing.IsActive = true;
        try
        {
            var result = await _workerService.ExecuteToolAsync(
                _module,
                _inputBox.Text,
                _apiManager,
                _referenceDataService,
                language: _settingsService.Current.Language);
            if (result.Ok)
            {
                _outputBox.Text = result.Output;
                _statusBar.Severity = InfoBarSeverity.Success;
                _statusBar.Title = "完成";
                _statusBar.Message = "工具已在 WinUI 原生执行器中完成。";
            }
            else
            {
                _outputBox.Text = result.Error ?? "未知错误";
                _statusBar.Severity = InfoBarSeverity.Error;
                _statusBar.Title = "执行失败";
                _statusBar.Message = result.Error ?? "工具执行失败。";
            }
        }
        finally
        {
            _progressRing.IsActive = false;
            _progressRing.Visibility = Visibility.Collapsed;
        }
    }

    private void RefreshExamples(IToolModule module)
    {
        _examplesPanel.Children.Clear();
        var examples = SampleInputs(module).ToArray();
        if (examples.Length == 0)
        {
            _examplesPanel.Visibility = Visibility.Collapsed;
            return;
        }

        _examplesPanel.Visibility = Visibility.Visible;
        _examplesPanel.Children.Add(ModernUi.Text("示例", 13, FontWeights.SemiBold, ModernUi.TextSecondary));
        foreach (var example in examples)
        {
            var button = new Button
            {
                Content = example.Label,
                Padding = new Thickness(10, 4, 10, 5),
                CornerRadius = new CornerRadius(6),
                BorderBrush = ModernUi.Stroke,
                Background = ModernUi.Surface
            };
            button.Click += (_, _) => _inputBox.Text = example.Input;
            ToolTipService.SetToolTip(button, example.Input);
            _examplesPanel.Children.Add(button);
        }
    }

    private void CopyResult()
    {
        var data = new DataPackage();
        data.SetText(_outputBox.Text ?? string.Empty);
        Clipboard.SetContent(data);
    }

    private async void BrowseInputFile()
    {
        if (_module is null || App.CurrentWindow is null)
        {
            return;
        }

        var picker = new FileOpenPicker();
        InitializeWithWindow.Initialize(picker, WindowNative.GetWindowHandle(App.CurrentWindow));
        foreach (var extension in FileTypeFilters(_module.Id))
        {
            picker.FileTypeFilter.Add(extension);
        }

        var file = await picker.PickSingleFileAsync();
        if (file is not null)
        {
            _inputBox.Text = file.Path;
        }
    }

    private void ShowNativeTool(Page page)
    {
        _standardToolHost.Visibility = Visibility.Collapsed;
        _nativeToolHost.Content = page;
        _nativeToolHost.Visibility = Visibility.Visible;
    }

    private static string BuildInputHint(IToolModule module)
    {
        return module.Id switch
        {
            "regex_tool" => "第一行输入正则表达式，第二行开始输入待匹配文本",
            "replace_text" or "batch_text_replace" => "第一行查找文本，第二行替换文本，第三行开始输入正文",
            "loan_emi_calculator" => "本金 年利率 月数，例如：100000 4.5 360",
            "bmi_calculator" => "体重kg 身高m，例如：70 1.75",
            "train_query" => "日期 出发站 到达站，例如：2026-05-25 北京 上海",
            "shelf_life" => "输入食品名，或输入“生产日期 保质期”，例如：2026-05-01 180天",
            "system_tool" => "输入 status、temp、path、env 或 process",
            "qrcode_scanner" or "image_processor" or "archive_tool" => "输入本地文件路径；支持带引号的路径",
            _ => module.Metadata.OfflineCapable ? "输入要处理的文本或参数" : "输入查询关键词、域名、IP 或城市"
        };
    }

    private static string DefaultInput(IToolModule module)
    {
        return module.Id switch
        {
            "json_formatter" => "{\"name\":\"YMhut Box\",\"runtime\":\"WinUI 3\"}",
            "regex_tool" => "\\bWinUI\\b\nYMhut Box WinUI 3",
            "loan_emi_calculator" => "100000 4.5 360",
            "bmi_calculator" => "70 1.75",
            "dns_query" => "example.com",
            "weather" => "北京",
            "train_query" => $"{DateTime.Today.AddDays(1):yyyy-MM-dd} 北京 上海",
            "system_tool" => "status",
            "shelf_life" => $"{DateTime.Today:yyyy-MM-dd} 180天",
            "car_info" => "京A12345",
            "sanguosha_skin" => "刘备",
            _ => string.Empty
        };
    }

    private static bool RequiresFilePath(string id)
    {
        return id is "qrcode_scanner" or "image_processor" or "archive_tool";
    }

    private static IReadOnlyList<string> FileTypeFilters(string id)
    {
        return id switch
        {
            "qrcode_scanner" or "image_processor" => [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp"],
            "archive_tool" => [".zip", ".tar"],
            _ => ["*"]
        };
    }

    private static IEnumerable<(string Label, string Input)> SampleInputs(IToolModule module)
    {
        return module.Id switch
        {
            "json_formatter" => [("JSON", "{\"name\":\"YMhut Box\",\"runtime\":\"WinUI 3\"}")],
            "regex_tool" => [("Regex", "\\bWinUI\\b\nYMhut Box WinUI 3")],
            "weather" => [("北京", "北京"), ("上海", "上海")],
            "train_query" => [("京沪", $"{DateTime.Today.AddDays(1):yyyy-MM-dd} 北京 上海")],
            "dns_query" => [("A 记录", "example.com")],
            "domain_price" or "rdap_domain_lookup" => [("域名", "example.com")],
            "rdap_ip_lookup" or "ip_info" or "ip_lookup" => [("IP", "8.8.8.8")],
            "shelf_life" => [("到期日", $"{DateTime.Today:yyyy-MM-dd} 180天"), ("牛奶", "牛奶")],
            "car_info" => [("车牌", "京A12345"), ("城市", "北京市")],
            "sanguosha_skin" => [("刘备", "刘备"), ("皮肤ID", "100101")],
            "system_tool" => [("状态", "status"), ("临时文件", "temp"), ("进程", "process")],
            "qrcode_scanner" => [("图片路径", "C:\\path\\to\\qrcode.png")],
            _ => []
        };
    }
}

public sealed record ToolDetailContext(IToolModule Module);
