using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using AxCopilot.Views;

namespace AxCopilot.Services;

public static partial class MarkdownRenderer
{
    /// <summary>코드 블록 UI 생성 (헤더 + 복사 버튼 + 코드)</summary>
    private static Border CreateCodeBlock(string code, string lang, Brush textColor, Brush codeBg, Brush accentColor)
    {
        var container = new Border
        {
            Background = codeBg,
            CornerRadius = new CornerRadius(10),
            Margin = new Thickness(0, 6, 0, 6),
            Padding = new Thickness(0)
        };

        var stack = new StackPanel();

        // 헤더 (언어 + 복사 버튼)
        var header = new Border
        {
            Background = new SolidColorBrush(Color.FromArgb(30, 255, 255, 255)),
            CornerRadius = new CornerRadius(10, 10, 0, 0),
            Padding = new Thickness(14, 6, 8, 6)
        };
        var headerGrid = new Grid();
        headerGrid.Children.Add(new TextBlock
        {
            Text = string.IsNullOrEmpty(lang) ? "code" : lang,
            FontSize = 11,
            Foreground = accentColor,
            FontWeight = FontWeights.SemiBold,
            VerticalAlignment = VerticalAlignment.Center
        });

        // 우측 버튼 패널
        var btnPanel = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            HorizontalAlignment = HorizontalAlignment.Right,
            VerticalAlignment = VerticalAlignment.Center,
        };

        var capturedCode = code;
        var capturedLang = lang;

        // 파일 저장 버튼
        var saveBtn = CreateCodeHeaderButton("\uE74E", "저장", textColor);
        saveBtn.Click += (_, _) =>
        {
            try
            {
                var ext = GetExtensionForLang(capturedLang);
                var dlg = new Microsoft.Win32.SaveFileDialog
                {
                    FileName = $"code{ext}",
                    Filter = $"코드 파일 (*{ext})|*{ext}|모든 파일 (*.*)|*.*",
                };
                if (dlg.ShowDialog() == true)
                    System.IO.File.WriteAllText(dlg.FileName, capturedCode);
            }
            catch (Exception) { }
        };
        btnPanel.Children.Add(saveBtn);

        // 전체화면 버튼
        var expandBtn = CreateCodeHeaderButton("\uE740", "확대", textColor);
        expandBtn.Click += (_, _) => ShowCodeFullScreen(capturedCode, capturedLang, codeBg, textColor);
        btnPanel.Children.Add(expandBtn);

        // 복사 버튼
        var copyBtn = CreateCodeHeaderButton("\uE8C8", "복사", textColor);
        copyBtn.Click += (_, _) => { try { Clipboard.SetText(capturedCode); } catch (Exception) { } };
        btnPanel.Children.Add(copyBtn);

        headerGrid.Children.Add(btnPanel);
        header.Child = headerGrid;
        stack.Children.Add(header);

        // 코드 본문 (라인 번호 + 구문 하이라이팅)
        var codeGrid = new Grid { Margin = new Thickness(0, 0, 0, 4) };
        codeGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        codeGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

        // 라인 번호
        var codeLines = code.Split('\n');
        var lineNumbers = new TextBlock
        {
            FontFamily = ThemeResourceHelper.CascadiaCode,
            FontSize = 12.5,
            Foreground = new SolidColorBrush(Color.FromArgb(0x50, 0xFF, 0xFF, 0xFF)),
            Padding = new Thickness(10, 10, 6, 14),
            LineHeight = 20,
            TextAlignment = TextAlignment.Right,
            Text = string.Join("\n", Enumerable.Range(1, codeLines.Length)),
        };
        Grid.SetColumn(lineNumbers, 0);
        codeGrid.Children.Add(lineNumbers);

        var codeText = new TextBlock
        {
            FontFamily = ThemeResourceHelper.CascadiaCode,
            FontSize = 12.5,
            Foreground = textColor,
            TextWrapping = TextWrapping.Wrap,
            Padding = new Thickness(8, 10, 14, 14),
            LineHeight = 20
        };
        ApplySyntaxHighlighting(codeText, code, lang, textColor);
        Grid.SetColumn(codeText, 1);
        codeGrid.Children.Add(codeText);

        stack.Children.Add(codeGrid);

        container.Child = stack;
        return container;
    }

    private static Button CreateCodeHeaderButton(string mdlIcon, string label, Brush fg)
    {
        return new Button
        {
            Background = Brushes.Transparent,
            BorderThickness = new Thickness(0),
            Cursor = System.Windows.Input.Cursors.Hand,
            VerticalAlignment = VerticalAlignment.Center,
            Padding = new Thickness(5, 2, 5, 2),
            Margin = new Thickness(2, 0, 0, 0),
            Content = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Children =
                {
                    new TextBlock
                    {
                        Text = mdlIcon,
                        FontFamily = ThemeResourceHelper.SegoeMdl2,
                        FontSize = 10, Foreground = fg, Opacity = 0.6,
                        VerticalAlignment = VerticalAlignment.Center,
                        Margin = new Thickness(0, 0, 3, 0),
                    },
                    new TextBlock { Text = label, FontSize = 10, Foreground = fg, Opacity = 0.6 },
                }
            }
        };
    }

    private static string GetExtensionForLang(string lang) => (lang ?? "").ToLowerInvariant() switch
    {
        "csharp" or "cs" => ".cs",
        "python" or "py" => ".py",
        "javascript" or "js" => ".js",
        "typescript" or "ts" => ".ts",
        "java" => ".java",
        "html" => ".html",
        "css" => ".css",
        "json" => ".json",
        "xml" => ".xml",
        "sql" => ".sql",
        "bash" or "sh" or "shell" => ".sh",
        "powershell" or "ps1" => ".ps1",
        "bat" or "cmd" => ".bat",
        "yaml" or "yml" => ".yml",
        "markdown" or "md" => ".md",
        "cpp" or "c++" => ".cpp",
        "c" => ".c",
        "go" => ".go",
        "rust" or "rs" => ".rs",
        _ => ".txt",
    };

    private static void ShowCodeFullScreen(string code, string lang, Brush codeBg, Brush textColor)
    {
        var win = new Window
        {
            Title = $"코드 — {(string.IsNullOrEmpty(lang) ? "code" : lang)}",
            Width = 900, Height = 650,
            WindowStartupLocation = WindowStartupLocation.CenterScreen,
            Background = codeBg is SolidColorBrush scb ? new SolidColorBrush(scb.Color) : Brushes.Black,
        };

        var grid = new Grid();
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

        var lines = code.Split('\n');

        var lineNumTb = new TextBlock
        {
            FontFamily = ThemeResourceHelper.CascadiaCode,
            FontSize = 13, LineHeight = 22,
            Foreground = new SolidColorBrush(Color.FromArgb(0x50, 0xFF, 0xFF, 0xFF)),
            Padding = new Thickness(16, 16, 8, 16),
            TextAlignment = TextAlignment.Right,
            Text = string.Join("\n", Enumerable.Range(1, lines.Length)),
        };
        Grid.SetColumn(lineNumTb, 0);
        grid.Children.Add(lineNumTb);

        var codeTb = new TextBlock
        {
            FontFamily = ThemeResourceHelper.CascadiaCode,
            FontSize = 13, LineHeight = 22,
            Foreground = textColor,
            TextWrapping = TextWrapping.Wrap,
            Padding = new Thickness(8, 16, 16, 16),
        };
        ApplySyntaxHighlighting(codeTb, code, lang, textColor);
        Grid.SetColumn(codeTb, 1);
        grid.Children.Add(codeTb);

        var sv = new ScrollViewer
        {
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
            HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
            Content = grid,
        };
        win.Content = sv;
        win.Show();
    }

}
