using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using AxCopilot.Services.Agent;

namespace AxCopilot.Views;

public partial class SkillGalleryWindow
{
    // ─── 스킬 상세 보기 팝업 ───────────────────────────────────────────────

    private void ShowSkillDetail(SkillDefinition skill)
    {
        var bgBrush  = TryFindResource("LauncherBackground") as Brush ?? Brushes.Black;
        var fgBrush  = TryFindResource("PrimaryText")   as Brush ?? Brushes.White;
        var subBrush = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var itemBg   = TryFindResource("ItemBackground") as Brush ?? Brushes.Transparent;
        var borderBr = TryFindResource("BorderColor")   as Brush ?? Brushes.Gray;

        var popup = new Window
        {
            Title   = $"/{skill.Name}",
            Width   = 580,
            Height  = 480,
            WindowStyle         = WindowStyle.None,
            AllowsTransparency  = true,
            Background          = Brushes.Transparent,
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            Owner = this,
        };

        var outerBorder = new Border
        {
            Background   = bgBrush,
            CornerRadius = new CornerRadius(12),
            BorderBrush  = borderBr,
            BorderThickness = new Thickness(1, 1, 1, 1),
            Effect = new System.Windows.Media.Effects.DropShadowEffect
            {
                BlurRadius  = 20,
                ShadowDepth = 4,
                Opacity     = 0.3,
                Color       = Colors.Black,
            },
        };

        var mainGrid = new Grid();
        mainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(44) });
        mainGrid.RowDefinitions.Add(new RowDefinition());

        // ── 타이틀바 ──
        var titleBar = new Border
        {
            CornerRadius = new CornerRadius(12, 12, 0, 0),
            Background   = itemBg,
        };
        titleBar.MouseLeftButtonDown += (_, e) =>
        {
            var pos = e.GetPosition(popup);
            if (pos.X > popup.ActualWidth - 50) return;
            popup.DragMove();
        };

        var titleGrid = new Grid { Margin = new Thickness(16, 0, 12, 0) };
        var titleLeft = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };
        titleLeft.Children.Add(new TextBlock
        {
            Text       = skill.Icon,
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize   = 14,
            Foreground = new SolidColorBrush(Color.FromRgb(0x4B, 0x5E, 0xFC)),
            VerticalAlignment = VerticalAlignment.Center,
            Margin     = new Thickness(0, 1, 8, 0),
        });
        titleLeft.Children.Add(new TextBlock
        {
            Text       = $"/{skill.Name}  {skill.Label}",
            FontSize   = 14,
            FontWeight = FontWeights.SemiBold,
            Foreground = fgBrush,
            VerticalAlignment = VerticalAlignment.Center,
        });
        titleGrid.Children.Add(titleLeft);

        var closeBtn = new Border
        {
            Width  = 28, Height = 28,
            CornerRadius = new CornerRadius(6),
            Cursor = Cursors.Hand,
            HorizontalAlignment = HorizontalAlignment.Right,
            VerticalAlignment   = VerticalAlignment.Center,
        };
        closeBtn.Child = new TextBlock
        {
            Text       = "\uE8BB",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize   = 10,
            Foreground = subBrush,
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment   = VerticalAlignment.Center,
        };
        closeBtn.MouseEnter += (s, _) => ((Border)s).Background =
            new SolidColorBrush(Color.FromArgb(0x33, 0xFF, 0x44, 0x44));
        closeBtn.MouseLeave += (s, _) => ((Border)s).Background = Brushes.Transparent;
        closeBtn.MouseLeftButtonUp += (_, _) => popup.Close();
        titleGrid.Children.Add(closeBtn);

        titleBar.Child = titleGrid;
        Grid.SetRow(titleBar, 0);

        // ── 본문: 스킬 정보 + 프롬프트 미리보기 ──
        var body = new ScrollViewer
        {
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
            Padding = new Thickness(20, 16, 20, 16),
        };

        var bodyPanel = new StackPanel();

        // 메타 정보
        var metaGrid = new Grid { Margin = new Thickness(0, 0, 0, 14) };
        metaGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(80) });
        metaGrid.ColumnDefinitions.Add(new ColumnDefinition());

        void AddMetaRow(string label, string value, int row)
        {
            if (string.IsNullOrEmpty(value)) return;
            metaGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            var lb = new TextBlock
            {
                Text = label, FontSize = 11.5, Foreground = subBrush,
                Margin = new Thickness(0, 2, 0, 2),
            };
            Grid.SetRow(lb, row); Grid.SetColumn(lb, 0);
            metaGrid.Children.Add(lb);

            var vb = new TextBlock
            {
                Text = value, FontSize = 11.5, Foreground = fgBrush,
                TextWrapping = TextWrapping.Wrap,
                Margin = new Thickness(0, 2, 0, 2),
            };
            Grid.SetRow(vb, row); Grid.SetColumn(vb, 1);
            metaGrid.Children.Add(vb);
        }

        var metaRow = 0;
        AddMetaRow("명령어", $"/{skill.Name}", metaRow++);
        AddMetaRow("라벨", skill.Label, metaRow++);
        AddMetaRow("설명", skill.Description, metaRow++);
        if (!string.IsNullOrEmpty(skill.Requires))
            AddMetaRow("런타임", skill.Requires, metaRow++);
        if (!string.IsNullOrEmpty(skill.AllowedTools))
            AddMetaRow("허용 도구", skill.AllowedTools, metaRow++);
        AddMetaRow("상태", skill.IsAvailable ? "✓ 사용 가능" : $"✗ {skill.UnavailableHint}", metaRow++);
        AddMetaRow("경로", skill.FilePath, metaRow++);

        bodyPanel.Children.Add(metaGrid);

        // 구분선
        bodyPanel.Children.Add(new Border
        {
            Height     = 1,
            Background = borderBr,
            Margin     = new Thickness(0, 4, 0, 12),
        });

        // 프롬프트 내용 미리보기
        bodyPanel.Children.Add(new TextBlock
        {
            Text       = "시스템 프롬프트 (미리보기)",
            FontSize   = 11,
            FontWeight = FontWeights.SemiBold,
            Foreground = subBrush,
            Margin     = new Thickness(0, 0, 0, 6),
        });

        var promptBorder = new Border
        {
            Background   = itemBg,
            CornerRadius = new CornerRadius(8),
            Padding      = new Thickness(12, 10, 12, 10),
        };
        var promptText = skill.SystemPrompt;
        if (promptText.Length > 2000)
            promptText = promptText[..2000] + "\n\n... (이하 생략)";

        promptBorder.Child = new TextBlock
        {
            Text         = promptText,
            FontSize     = 11.5,
            FontFamily   = ThemeResourceHelper.ConsolasCode,
            Foreground   = fgBrush,
            TextWrapping = TextWrapping.Wrap,
            Opacity      = 0.85,
        };
        bodyPanel.Children.Add(promptBorder);

        body.Content = bodyPanel;
        Grid.SetRow(body, 1);

        mainGrid.Children.Add(titleBar);
        mainGrid.Children.Add(body);
        outerBorder.Child = mainGrid;
        popup.Content = outerBorder;

        popup.ShowDialog();
    }
}
