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
{
    // ─── AX Agent 서브탭 전환 ───────────────────────────────────────────

    private void AgentSubTab_Checked(object sender, RoutedEventArgs e)
    {
        if (AgentPanelCommon == null) return; // 초기화 전 방어
        AgentPanelCommon.Visibility     = AgentTabCommon.IsChecked     == true ? Visibility.Visible : Visibility.Collapsed;
        AgentPanelChat.Visibility       = AgentTabChat.IsChecked       == true ? Visibility.Visible : Visibility.Collapsed;
        AgentPanelCoworkCode.Visibility = AgentTabCoworkCode.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
        AgentPanelCowork.Visibility     = AgentTabCowork.IsChecked     == true ? Visibility.Visible : Visibility.Collapsed;
        AgentPanelCode.Visibility       = AgentTabCode.IsChecked       == true ? Visibility.Visible : Visibility.Collapsed;
        if (AgentPanelDev != null)
            AgentPanelDev.Visibility    = AgentTabDev.IsChecked        == true ? Visibility.Visible : Visibility.Collapsed;
        if (AgentPanelEtc != null)
            AgentPanelEtc.Visibility    = AgentTabEtc.IsChecked        == true ? Visibility.Visible : Visibility.Collapsed;
        if (AgentPanelTools != null)
        {
            var show = AgentTabTools.IsChecked == true;
            AgentPanelTools.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
            if (show) LoadToolCards();
        }
    }

    // ─── 도구 관리 카드 UI ──────────────────────────────────────────────

    private bool _toolCardsLoaded;
    private HashSet<string> _disabledTools = new(StringComparer.OrdinalIgnoreCase);

    /// <summary>도구 카드 UI를 카테고리별로 생성합니다.</summary>
    private void LoadToolCards()
    {
        if (_toolCardsLoaded || ToolCardsPanel == null) return;
        _toolCardsLoaded = true;

        var app = CurrentApp;
        var settings = app?.SettingsService?.Settings.Llm;
        using var tools = Services.Agent.ToolRegistry.CreateDefault();
        _disabledTools = new HashSet<string>(settings?.DisabledTools ?? new(), StringComparer.OrdinalIgnoreCase);
        var disabled = _disabledTools;

        // 카테고리 매핑
        var categories = new Dictionary<string, List<Services.Agent.IAgentTool>>
        {
            ["파일/검색"] = new(),
            ["문서 생성"] = new(),
            ["문서 품질"] = new(),
            ["코드/개발"] = new(),
            ["데이터/유틸"] = new(),
            ["시스템"] = new(),
        };

        var toolCategoryMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
        {
            // 파일/검색
            ["file_read"] = "파일/검색", ["file_write"] = "파일/검색", ["file_edit"] = "파일/검색",
            ["glob"] = "파일/검색", ["grep"] = "파일/검색", ["folder_map"] = "파일/검색",
            ["document_read"] = "파일/검색", ["file_watch"] = "파일/검색",
            // 문서 생성
            ["excel_skill"] = "문서 생성", ["docx_skill"] = "문서 생성", ["csv_skill"] = "문서 생성",
            ["markdown_skill"] = "문서 생성", ["html_skill"] = "문서 생성", ["chart_skill"] = "문서 생성",
            ["batch_skill"] = "문서 생성", ["pptx_skill"] = "문서 생성",
            ["document_planner"] = "문서 생성", ["document_assembler"] = "문서 생성",
            // 문서 품질
            ["document_review"] = "문서 품질", ["format_convert"] = "문서 품질",
            ["template_render"] = "문서 품질", ["text_summarize"] = "문서 품질",
            // 코드/개발
            ["dev_env_detect"] = "코드/개발", ["build_run"] = "코드/개발", ["git_tool"] = "코드/개발",
            ["lsp"] = "코드/개발", ["sub_agent"] = "코드/개발", ["wait_agents"] = "코드/개발",
            ["code_search"] = "코드/개발", ["test_loop"] = "코드/개발",
            ["code_review"] = "코드/개발", ["project_rule"] = "코드/개발",
            // 시스템
            ["process"] = "시스템", ["skill_manager"] = "시스템", ["memory"] = "시스템",
            ["clipboard"] = "시스템", ["notify"] = "시스템", ["env"] = "시스템",
            ["image_analyze"] = "시스템",
        };

        foreach (var tool in tools.All)
        {
            var cat = toolCategoryMap.TryGetValue(tool.Name, out var c) ? c : "데이터/유틸";
            if (categories.ContainsKey(cat))
                categories[cat].Add(tool);
            else
                categories["데이터/유틸"].Add(tool);
        }

        var accentBrush = TryFindResource("AccentColor") as Brush ?? Brushes.CornflowerBlue;
        var secondaryText = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var itemBg = TryFindResource("ItemBackground") as Brush ?? new SolidColorBrush(Color.FromRgb(0xF5, 0xF5, 0xF8));

        foreach (var kv in categories)
        {
            if (kv.Value.Count == 0) continue;

            // 카테고리 헤더
            var header = new TextBlock
            {
                Text = $"{kv.Key}  ({kv.Value.Count})",
                FontSize = 13, FontWeight = FontWeights.SemiBold,
                Foreground = TryFindResource("PrimaryText") as Brush ?? Brushes.Black,
                Margin = new Thickness(0, 8, 0, 6),
            };
            ToolCardsPanel.Children.Add(header);

            // 카드 WrapPanel
            var wrap = new WrapPanel { Margin = new Thickness(0, 0, 0, 4) };
            foreach (var tool in kv.Value.OrderBy(t => t.Name))
            {
                var isEnabled = !disabled.Contains(tool.Name);
                var card = CreateToolCard(tool, isEnabled, disabled, accentBrush, secondaryText, itemBg);
                wrap.Children.Add(card);
            }
            ToolCardsPanel.Children.Add(wrap);
        }

        // MCP 서버 상태
        LoadMcpStatus();
    }

    /// <summary>개별 도구 카드를 생성합니다 (이름 + 설명 + 토글).</summary>
    private Border CreateToolCard(Services.Agent.IAgentTool tool, bool isEnabled,
        HashSet<string> disabled, Brush accentBrush, Brush secondaryText, Brush itemBg)
    {
        var card = new Border
        {
            Background = itemBg,
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(10, 8, 10, 8),
            Margin = new Thickness(0, 0, 8, 8),
            Width = 240,
            BorderBrush = isEnabled ? Brushes.Transparent : new SolidColorBrush(Color.FromArgb(0x30, 0xDC, 0x26, 0x26)),
            BorderThickness = new Thickness(1),
        };

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

        // 이름 + 설명
        var textStack = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
        var nameBlock = new TextBlock
        {
            Text = tool.Name,
            FontSize = 12, FontWeight = FontWeights.SemiBold,
            Foreground = TryFindResource("PrimaryText") as Brush ?? Brushes.Black,
            TextTrimming = TextTrimming.CharacterEllipsis,
        };
        textStack.Children.Add(nameBlock);

        var desc = tool.Description;
        if (desc.Length > 50) desc = desc[..50] + "…";
        var descBlock = new TextBlock
        {
            Text = desc,
            FontSize = 10.5,
            Foreground = secondaryText,
            TextTrimming = TextTrimming.CharacterEllipsis,
            Margin = new Thickness(0, 2, 0, 0),
        };
        textStack.Children.Add(descBlock);
        Grid.SetColumn(textStack, 0);
        grid.Children.Add(textStack);

        // 토글 (CheckBox + ToggleSwitch 스타일)
        var toggle = new CheckBox
        {
            IsChecked = isEnabled,
            Style = TryFindResource("ToggleSwitch") as Style,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(8, 0, 0, 0),
        };
        toggle.Checked += (_, _) =>
        {
            disabled.Remove(tool.Name);
            card.BorderBrush = Brushes.Transparent;
        };
        toggle.Unchecked += (_, _) =>
        {
            disabled.Add(tool.Name);
            card.BorderBrush = new SolidColorBrush(Color.FromArgb(0x30, 0xDC, 0x26, 0x26));
        };
        Grid.SetColumn(toggle, 1);
        grid.Children.Add(toggle);

        card.Child = grid;
        return card;
    }

    /// <summary>MCP 서버 연결 상태 표시를 생성합니다.</summary>
    private void LoadMcpStatus()
    {
        if (McpStatusPanel == null) return;
        McpStatusPanel.Children.Clear();

        var app = CurrentApp;
        var settings = app?.SettingsService?.Settings.Llm;
        var mcpServers = settings?.McpServers;

        if (mcpServers == null || mcpServers.Count == 0)
        {
            McpStatusPanel.Children.Add(new TextBlock
            {
                Text = "등록된 MCP 서버가 없습니다.",
                FontSize = 12,
                Foreground = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray,
                Margin = new Thickness(0, 4, 0, 0),
            });
            return;
        }

        var itemBg = TryFindResource("ItemBackground") as Brush ?? new SolidColorBrush(Color.FromRgb(0xF5, 0xF5, 0xF8));

        foreach (var server in mcpServers)
        {
            var row = new Border
            {
                Background = itemBg,
                CornerRadius = new CornerRadius(8),
                Padding = new Thickness(12, 8, 12, 8),
                Margin = new Thickness(0, 0, 0, 6),
            };

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

            // 상태 아이콘
            var statusDot = new Border
            {
                Width = 8, Height = 8,
                CornerRadius = new CornerRadius(4),
                Background = new SolidColorBrush(Color.FromRgb(0x34, 0xA8, 0x53)), // 녹색 (등록됨)
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 8, 0),
            };
            Grid.SetColumn(statusDot, 0);
            grid.Children.Add(statusDot);

            // 서버 이름 + 명령
            var infoStack = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
            infoStack.Children.Add(new TextBlock
            {
                Text = server.Name ?? "(이름 없음)",
                FontSize = 12, FontWeight = FontWeights.SemiBold,
                Foreground = TryFindResource("PrimaryText") as Brush ?? Brushes.Black,
            });
            infoStack.Children.Add(new TextBlock
            {
                Text = server.Command ?? "",
                FontSize = 10.5,
                Foreground = TryFindResource("SecondaryText") as Brush ?? Brushes.Gray,
                TextTrimming = TextTrimming.CharacterEllipsis,
            });
            Grid.SetColumn(infoStack, 1);
            grid.Children.Add(infoStack);

            // 상태 텍스트
            var statusText = new TextBlock
            {
                Text = "등록됨",
                FontSize = 11,
                Foreground = new SolidColorBrush(Color.FromRgb(0x34, 0xA8, 0x53)),
                VerticalAlignment = VerticalAlignment.Center,
            };
            Grid.SetColumn(statusText, 2);
            grid.Children.Add(statusText);

            row.Child = grid;
            McpStatusPanel.Children.Add(row);
        }
    }
}
