using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using AxCopilot.Services;
using AxCopilot.ViewModels;

namespace AxCopilot.Views;

public partial class SettingsWindow
{
    // ─── 스킬 목록 패널 ─────────────────────────────────────────────────────

    private void BuildSkillListSection(ref int insertIdx)
    {
        if (AgentEtcContent == null) return;

        var skills = Services.Agent.SkillService.Skills;
        if (skills.Count == 0) return;

        var accentColor = ThemeResourceHelper.HexColor("#4B5EFC");
        var subtleText = ThemeResourceHelper.HexColor("#6666AA");

        // 스킬 콘텐츠를 모아서 접기/열기 섹션에 넣기
        var skillItems = new List<UIElement>();

        // 설명
        skillItems.Add(new TextBlock
        {
            Text = "/ 명령으로 호출할 수 있는 스킬 목록입니다. 앱 내장 + 사용자 추가 스킬이 포함됩니다.\n" +
                   "(스킬은 사용자가 직접 /명령어를 입력해야 실행됩니다. LLM이 자동 호출하지 않습니다.)",
            FontSize = 11,
            Foreground = new SolidColorBrush(subtleText),
            Margin = new Thickness(2, 0, 0, 10),
            TextWrapping = TextWrapping.Wrap,
        });

        // 내장 스킬 / 고급 스킬 분류
        var builtIn = skills.Where(s => string.IsNullOrEmpty(s.Requires)).ToList();
        var advanced = skills.Where(s => !string.IsNullOrEmpty(s.Requires)).ToList();

        // 내장 스킬 카드
        if (builtIn.Count > 0)
        {
            var card = CreateSkillGroupCard("내장 스킬", "\uE768", "#34D399", builtIn);
            skillItems.Add(card);
        }

        // 고급 스킬 (런타임 의존) 카드
        if (advanced.Count > 0)
        {
            var card = CreateSkillGroupCard("고급 스킬 (런타임 필요)", "\uE9D9", "#A78BFA", advanced);
            skillItems.Add(card);
        }

        // ── 스킬 가져오기/내보내기 버튼 ──
        var btnPanel = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Margin = new Thickness(2, 4, 0, 10),
        };

        // 가져오기 버튼
        var importBtn = new Border
        {
            Background = ThemeResourceHelper.HexBrush("#4B5EFC"),
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(14, 7, 14, 7),
            Margin = new Thickness(0, 0, 8, 0),
            Cursor = Cursors.Hand,
        };
        var importContent = new StackPanel { Orientation = Orientation.Horizontal };
        importContent.Children.Add(new TextBlock
        {
            Text = "\uE8B5",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 12,
            Foreground = Brushes.White,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
        });
        importContent.Children.Add(new TextBlock
        {
            Text = "스킬 가져오기 (.zip)",
            FontSize = 12,
            FontWeight = FontWeights.SemiBold,
            Foreground = Brushes.White,
            VerticalAlignment = VerticalAlignment.Center,
        });
        importBtn.Child = importContent;
        importBtn.MouseLeftButtonUp += SkillImport_Click;
        importBtn.MouseEnter += (s, _) => ((Border)s).Opacity = 0.85;
        importBtn.MouseLeave += (s, _) => ((Border)s).Opacity = 1.0;
        btnPanel.Children.Add(importBtn);

        // 내보내기 버튼
        var exportBtn = new Border
        {
            Background = ThemeResourceHelper.HexBrush("#F0F1F5"),
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(14, 7, 14, 7),
            Cursor = Cursors.Hand,
        };
        var exportContent = new StackPanel { Orientation = Orientation.Horizontal };
        exportContent.Children.Add(new TextBlock
        {
            Text = "\uEDE1",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 12,
            Foreground = ThemeResourceHelper.HexBrush("#555"),
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
        });
        exportContent.Children.Add(new TextBlock
        {
            Text = "스킬 내보내기",
            FontSize = 12,
            FontWeight = FontWeights.SemiBold,
            Foreground = ThemeResourceHelper.HexBrush("#444"),
            VerticalAlignment = VerticalAlignment.Center,
        });
        exportBtn.Child = exportContent;
        exportBtn.MouseLeftButtonUp += SkillExport_Click;
        exportBtn.MouseEnter += (s, _) => ((Border)s).Opacity = 0.85;
        exportBtn.MouseLeave += (s, _) => ((Border)s).Opacity = 1.0;
        btnPanel.Children.Add(exportBtn);

        skillItems.Add(btnPanel);

        // ── 갤러리/통계 링크 버튼 ──
        var linkPanel = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Margin = new Thickness(2, 0, 0, 12),
        };

        var galleryBtn = new Border
        {
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(14, 7, 14, 7),
            Margin = new Thickness(0, 0, 8, 0),
            Background = new SolidColorBrush(Color.FromArgb(0x18, 0x4B, 0x5E, 0xFC)),
            Cursor = Cursors.Hand,
        };
        var galleryContent = new StackPanel { Orientation = Orientation.Horizontal };
        galleryContent.Children.Add(new TextBlock
        {
            Text = "\uE768",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 12,
            Foreground = ThemeResourceHelper.HexBrush("#4B5EFC"),
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
        });
        galleryContent.Children.Add(new TextBlock
        {
            Text = "스킬 갤러리 열기",
            FontSize = 12,
            FontWeight = FontWeights.SemiBold,
            Foreground = ThemeResourceHelper.HexBrush("#4B5EFC"),
        });
        galleryBtn.Child = galleryContent;
        galleryBtn.MouseLeftButtonUp += (_, _) =>
        {
            var win = new SkillGalleryWindow();
            win.Owner = Window.GetWindow(this);
            win.ShowDialog();
        };
        galleryBtn.MouseEnter += (s, _) => ((Border)s).Opacity = 0.8;
        galleryBtn.MouseLeave += (s, _) => ((Border)s).Opacity = 1.0;
        linkPanel.Children.Add(galleryBtn);

        var statsBtn = new Border
        {
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(14, 7, 14, 7),
            Background = new SolidColorBrush(Color.FromArgb(0x18, 0xA7, 0x8B, 0xFA)),
            Cursor = Cursors.Hand,
        };
        var statsContent = new StackPanel { Orientation = Orientation.Horizontal };
        statsContent.Children.Add(new TextBlock
        {
            Text = "\uE9D9",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 12,
            Foreground = ThemeResourceHelper.HexBrush("#A78BFA"),
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
        });
        statsContent.Children.Add(new TextBlock
        {
            Text = "실행 통계 보기",
            FontSize = 12,
            FontWeight = FontWeights.SemiBold,
            Foreground = ThemeResourceHelper.HexBrush("#A78BFA"),
        });
        statsBtn.Child = statsContent;
        statsBtn.MouseLeftButtonUp += (_, _) =>
        {
            var win = new AgentStatsDashboardWindow();
            win.Owner = Window.GetWindow(this);
            win.ShowDialog();
        };
        statsBtn.MouseEnter += (s, _) => ((Border)s).Opacity = 0.8;
        statsBtn.MouseLeave += (s, _) => ((Border)s).Opacity = 1.0;
        linkPanel.Children.Add(statsBtn);

        skillItems.Add(linkPanel);

        // ── 스킬 섹션 직접 추가 ──
        // 스킬 헤더
        var skillHeader = new TextBlock
        {
            Text = $"슬래시 스킬 ({skills.Count})",
            FontSize = 13,
            FontWeight = FontWeights.SemiBold,
            Foreground = TryFindResource("PrimaryText") as Brush ?? Brushes.White,
            Margin = new Thickness(2, 16, 0, 8),
        };
        AgentEtcContent.Children.Insert(insertIdx++, skillHeader);
        foreach (var item in skillItems)
            AgentEtcContent.Children.Insert(insertIdx++, item);
    }

    private Border CreateSkillGroupCard(string title, string icon, string colorHex,
        List<Services.Agent.SkillDefinition> skills)
    {
        var color = ThemeResourceHelper.HexColor(colorHex);
        var card = new Border
        {
            Background = TryFindResource("ItemBackground") as Brush ?? Brushes.White,
            CornerRadius = new CornerRadius(10),
            Padding = new Thickness(14, 10, 14, 10),
            Margin = new Thickness(0, 0, 0, 6),
        };

        var panel = new StackPanel();

        // 스킬 아이템 패널 (접기/열기 대상)
        var skillItemsPanel = new StackPanel { Visibility = Visibility.Collapsed };

        // 접기/열기 화살표
        var arrow = new TextBlock
        {
            Text = "\uE70D",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 9,
            Foreground = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
            RenderTransformOrigin = new Point(0.5, 0.5),
            RenderTransform = new RotateTransform(0),
        };

        // 카테고리 헤더 (클릭 가능)
        var catHeader = new Border
        {
            Background = Brushes.Transparent,
            Cursor = Cursors.Hand,
        };
        var catHeaderPanel = new StackPanel { Orientation = Orientation.Horizontal };
        catHeaderPanel.Children.Add(arrow);
        catHeaderPanel.Children.Add(new TextBlock
        {
            Text = icon,
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 14,
            Foreground = new SolidColorBrush(color),
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 8, 0),
        });
        catHeaderPanel.Children.Add(new TextBlock
        {
            Text = $"{title}  ({skills.Count})",
            FontSize = 12.5,
            FontWeight = FontWeights.SemiBold,
            Foreground = TryFindResource("PrimaryText") as Brush
                         ?? ThemeResourceHelper.HexBrush("#1A1B2E"),
            VerticalAlignment = VerticalAlignment.Center,
        });
        catHeader.Child = catHeaderPanel;

        // 클릭 시 접기/열기 토글
        catHeader.MouseLeftButtonDown += (s, e) =>
        {
            e.Handled = true;
            bool isVisible = skillItemsPanel.Visibility == Visibility.Visible;
            skillItemsPanel.Visibility = isVisible ? Visibility.Collapsed : Visibility.Visible;
            arrow.RenderTransform = new RotateTransform(isVisible ? 0 : 90);
        };

        panel.Children.Add(catHeader);

        // 구분선
        skillItemsPanel.Children.Add(new Border
        {
            Height = 1,
            Background = TryFindResource("BorderColor") as Brush
                         ?? ThemeResourceHelper.HexBrush("#F0F0F4"),
            Margin = new Thickness(0, 2, 0, 4),
        });

        // 스킬 아이템
        foreach (var skill in skills)
        {
            var row = new StackPanel { Margin = new Thickness(0, 4, 0, 4) };

            // 위 줄: 스킬 명칭 + 가용성 뱃지
            var namePanel = new StackPanel { Orientation = Orientation.Horizontal };
            namePanel.Children.Add(new TextBlock
            {
                Text = $"/{skill.Name}",
                FontSize = 12,
                FontFamily = ThemeResourceHelper.ConsolasCode,
                Foreground = skill.IsAvailable
                    ? (TryFindResource("AccentColor") as Brush ?? ThemeResourceHelper.HexBrush("#4B5EFC"))
                    : Brushes.Gray,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(4, 0, 8, 0),
                Opacity = skill.IsAvailable ? 1.0 : 0.5,
            });

            if (!skill.IsAvailable && !string.IsNullOrEmpty(skill.Requires))
            {
                namePanel.Children.Add(new Border
                {
                    Background = new SolidColorBrush(Color.FromArgb(0x20, 0xF8, 0x71, 0x71)),
                    CornerRadius = new CornerRadius(4),
                    Padding = new Thickness(5, 1, 5, 1),
                    VerticalAlignment = VerticalAlignment.Center,
                    Child = new TextBlock
                    {
                        Text = skill.UnavailableHint,
                        FontSize = 9,
                        Foreground = new SolidColorBrush(Color.FromRgb(0xF8, 0x71, 0x71)),
                        FontWeight = FontWeights.SemiBold,
                    },
                });
            }
            else if (skill.IsAvailable && !string.IsNullOrEmpty(skill.Requires))
            {
                namePanel.Children.Add(new Border
                {
                    Background = new SolidColorBrush(Color.FromArgb(0x20, 0x34, 0xD3, 0x99)),
                    CornerRadius = new CornerRadius(4),
                    Padding = new Thickness(5, 1, 5, 1),
                    VerticalAlignment = VerticalAlignment.Center,
                    Child = new TextBlock
                    {
                        Text = "✓ 사용 가능",
                        FontSize = 9,
                        Foreground = new SolidColorBrush(Color.FromRgb(0x34, 0xD3, 0x99)),
                        FontWeight = FontWeights.SemiBold,
                    },
                });
            }

            row.Children.Add(namePanel);

            // 아래 줄: 설명 (뱃지와 구분되도록 위 여백 추가)
            row.Children.Add(new TextBlock
            {
                Text = $"{skill.Label} — {skill.Description}",
                FontSize = 11.5,
                Foreground = TryFindResource("SecondaryText") as Brush
                             ?? ThemeResourceHelper.HexBrush("#6666AA"),
                TextWrapping = TextWrapping.Wrap,
                Margin = new Thickness(4, 3, 0, 0),
                Opacity = skill.IsAvailable ? 1.0 : 0.5,
            });

            skillItemsPanel.Children.Add(row);
        }

        panel.Children.Add(skillItemsPanel);
        card.Child = panel;
        return card;
    }

}
