using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace AxCopilot.Views;

public partial class SettingsWindow
{
    // ─── MCP 서버 관리 + 고급 설정 ──────────────────────────────────────────

    // ─── MCP 서버 관리 ─────────────────────────────────────────────────
    private void BtnAddMcpServer_Click(object sender, RoutedEventArgs e)
    {
        var dlg = new InputDialog("MCP 서버 추가", "서버 이름:", placeholder: "예: my-mcp-server");
        dlg.Owner = this;
        if (dlg.ShowDialog() != true || string.IsNullOrWhiteSpace(dlg.ResponseText)) return;

        var name = dlg.ResponseText.Trim();
        var cmdDlg = new InputDialog("MCP 서버 추가", "실행 명령:", placeholder: "예: npx -y @anthropic/mcp-server");
        cmdDlg.Owner = this;
        if (cmdDlg.ShowDialog() != true || string.IsNullOrWhiteSpace(cmdDlg.ResponseText)) return;

        var entry = new Models.McpServerEntry { Name = name, Command = cmdDlg.ResponseText.Trim(), Enabled = true };
        _vm.Service.Settings.Llm.McpServers.Add(entry);
        BuildMcpServerCards();
    }

    private void BuildMcpServerCards()
    {
        if (McpServerListPanel == null) return;
        McpServerListPanel.Children.Clear();

        var servers = _vm.Service.Settings.Llm.McpServers;
        var primaryText = TryFindResource("PrimaryText") as System.Windows.Media.Brush ?? System.Windows.Media.Brushes.Black;
        var secondaryText = TryFindResource("SecondaryText") as System.Windows.Media.Brush ?? System.Windows.Media.Brushes.Gray;
        var accentBrush = TryFindResource("AccentColor") as System.Windows.Media.Brush ?? System.Windows.Media.Brushes.Blue;

        for (int i = 0; i < servers.Count; i++)
        {
            var srv = servers[i];
            var idx = i;

            var card = new Border
            {
                Background = TryFindResource("ItemBackground") as System.Windows.Media.Brush,
                CornerRadius = new CornerRadius(10),
                Padding = new Thickness(14, 10, 14, 10),
                Margin = new Thickness(0, 4, 0, 0),
                BorderBrush = TryFindResource("BorderColor") as System.Windows.Media.Brush,
                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 info = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
            info.Children.Add(new TextBlock
            {
                Text = srv.Name, FontSize = 13.5, FontWeight = FontWeights.SemiBold, Foreground = primaryText,
            });
            var detailSp = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 0, 0) };
            detailSp.Children.Add(new Border
            {
                Background = srv.Enabled ? accentBrush : System.Windows.Media.Brushes.Gray,
                CornerRadius = new CornerRadius(4), Padding = new Thickness(6, 1, 6, 1), Margin = new Thickness(0, 0, 8, 0), Opacity = 0.8,
                Child = new TextBlock { Text = srv.Enabled ? "활성" : "비활성", FontSize = 10, Foreground = System.Windows.Media.Brushes.White, FontWeight = FontWeights.SemiBold },
            });
            detailSp.Children.Add(new TextBlock
            {
                Text = $"{srv.Command} {string.Join(" ", srv.Args)}", FontSize = 11,
                Foreground = secondaryText, VerticalAlignment = VerticalAlignment.Center,
                MaxWidth = 300, TextTrimming = TextTrimming.CharacterEllipsis,
            });
            info.Children.Add(detailSp);
            Grid.SetColumn(info, 0);
            grid.Children.Add(info);

            var btnPanel = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };

            // 활성/비활성 토글
            var toggleBtn = new Button
            {
                Content = srv.Enabled ? "\uE73E" : "\uE711",
                FontFamily = new System.Windows.Media.FontFamily("Segoe MDL2 Assets"),
                FontSize = 12, ToolTip = srv.Enabled ? "비활성화" : "활성화",
                Background = System.Windows.Media.Brushes.Transparent, BorderThickness = new Thickness(0),
                Foreground = srv.Enabled ? accentBrush : System.Windows.Media.Brushes.Gray,
                Padding = new Thickness(6, 4, 6, 4), Cursor = Cursors.Hand,
            };
            toggleBtn.Click += (_, _) => { servers[idx].Enabled = !servers[idx].Enabled; BuildMcpServerCards(); };
            btnPanel.Children.Add(toggleBtn);

            // 삭제
            var delBtn = new Button
            {
                Content = "\uE74D", FontFamily = new System.Windows.Media.FontFamily("Segoe MDL2 Assets"),
                FontSize = 12, ToolTip = "삭제",
                Background = System.Windows.Media.Brushes.Transparent, BorderThickness = new Thickness(0),
                Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xDD, 0x44, 0x44)),
                Padding = new Thickness(6, 4, 6, 4), Cursor = Cursors.Hand,
            };
            delBtn.Click += (_, _) => { servers.RemoveAt(idx); BuildMcpServerCards(); };
            btnPanel.Children.Add(delBtn);

            Grid.SetColumn(btnPanel, 1);
            grid.Children.Add(btnPanel);
            card.Child = grid;
            McpServerListPanel.Children.Add(card);
        }
    }

    // ─── 감사 로그 폴더 열기 ────────────────────────────────────────────
    private void BtnOpenAuditLog_Click(object sender, RoutedEventArgs e)
    {
        try { System.Diagnostics.Process.Start("explorer.exe", Services.AuditLogService.GetAuditFolder()); } catch (Exception) { }
    }

    // ─── 폴백/MCP 텍스트 박스 로드/저장 ───────────────────────────────────
    private void BuildFallbackModelsPanel()
    {
        if (FallbackModelsPanel == null) return;
        FallbackModelsPanel.Children.Clear();

        var llm = _vm.Service.Settings.Llm;
        var fallbacks = llm.FallbackModels;
        var toggleStyle = TryFindResource("ToggleSwitch") as Style;

        // 서비스별로 모델 수집 (순서 고정: Ollama → vLLM → Gemini → Claude)
        var sections = new (string Service, string Label, string Color, List<string> Models)[]
        {
            ("ollama", "Ollama", "#107C10", new()),
            ("vllm",   "vLLM",   "#0078D4", new()),
            ("gemini", "Gemini", "#4285F4", new()),
            ("claude", "Claude", "#8B5CF6", new()),
        };

        // RegisteredModels → ViewModel과 AppSettings 양쪽에서 수집 (저장 전에도 반영)
        // 1) ViewModel의 RegisteredModels (UI에서 방금 추가한 것 포함)
        foreach (var row in _vm.RegisteredModels)
        {
            var svc = (row.Service ?? "").ToLowerInvariant();
            var modelName = !string.IsNullOrEmpty(row.Alias) ? row.Alias : row.EncryptedModelName;
            var section = sections.FirstOrDefault(s => s.Service == svc);
            if (section.Models != null && !string.IsNullOrEmpty(modelName) && !section.Models.Contains(modelName))
                section.Models.Add(modelName);
        }
        // 2) AppSettings의 RegisteredModels (기존 저장된 것 — ViewModel에 없는 경우 보완)
        foreach (var m in llm.RegisteredModels)
        {
            var svc = (m.Service ?? "").ToLowerInvariant();
            var modelName = !string.IsNullOrEmpty(m.Alias) ? m.Alias : m.EncryptedModelName;
            var section = sections.FirstOrDefault(s => s.Service == svc);
            if (section.Models != null && !string.IsNullOrEmpty(modelName) && !section.Models.Contains(modelName))
                section.Models.Add(modelName);
        }

        // 현재 활성 모델 추가 (중복 제거)
        if (!string.IsNullOrEmpty(llm.OllamaModel) && !sections[0].Models.Contains(llm.OllamaModel))
            sections[0].Models.Add(llm.OllamaModel);
        if (!string.IsNullOrEmpty(llm.VllmModel) && !sections[1].Models.Contains(llm.VllmModel))
            sections[1].Models.Add(llm.VllmModel);

        // Gemini/Claude 고정 모델 목록
        foreach (var gm in new[] { "gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash", "gemini-1.5-pro", "gemini-1.5-flash" })
            if (!sections[2].Models.Contains(gm)) sections[2].Models.Add(gm);
        foreach (var cm in new[] { "claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5", "claude-sonnet-4-5" })
            if (!sections[3].Models.Contains(cm)) sections[3].Models.Add(cm);

        // 렌더링 — 모델이 없는 섹션도 헤더는 표시
        foreach (var (service, svcLabel, svcColor, models) in sections)
        {
            FallbackModelsPanel.Children.Add(new TextBlock
            {
                Text = svcLabel,
                FontSize = 11, FontWeight = FontWeights.SemiBold,
                Foreground = BrushFromHex(svcColor),
                Margin = new Thickness(0, 8, 0, 4),
            });

            if (models.Count == 0)
            {
                FallbackModelsPanel.Children.Add(new TextBlock
                {
                    Text = "등록된 모델 없음",
                    FontSize = 11, Foreground = Brushes.Gray, FontStyle = FontStyles.Italic,
                    Margin = new Thickness(8, 2, 0, 4),
                });
                continue;
            }

            foreach (var modelName in models)
            {
                var fullKey = $"{service}:{modelName}";

                var row = new Grid { Margin = new Thickness(8, 2, 0, 2) };
                row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

                var label = new TextBlock
                {
                    Text = modelName, FontSize = 12, FontFamily = ThemeResourceHelper.ConsolasCourierNew,
                    VerticalAlignment = VerticalAlignment.Center,
                    Foreground = TryFindResource("PrimaryText") as Brush ?? Brushes.Black,
                };
                Grid.SetColumn(label, 0);
                row.Children.Add(label);

                var captured = fullKey;
                var cb = new CheckBox
                {
                    IsChecked = fallbacks.Contains(fullKey, StringComparer.OrdinalIgnoreCase),
                    HorizontalAlignment = HorizontalAlignment.Right,
                    VerticalAlignment = VerticalAlignment.Center,
                };
                if (toggleStyle != null) cb.Style = toggleStyle;
                cb.Checked += (_, _) =>
                {
                    if (!fallbacks.Contains(captured)) fallbacks.Add(captured);
                    FallbackModelsBox.Text = string.Join("\n", fallbacks);
                };
                cb.Unchecked += (_, _) =>
                {
                    fallbacks.RemoveAll(x => x.Equals(captured, StringComparison.OrdinalIgnoreCase));
                    FallbackModelsBox.Text = string.Join("\n", fallbacks);
                };
                Grid.SetColumn(cb, 1);
                row.Children.Add(cb);

                FallbackModelsPanel.Children.Add(row);
            }
        }
    }

    private void LoadAdvancedSettings()
    {
        var llm = _vm.Service.Settings.Llm;
        if (FallbackModelsBox != null)
            FallbackModelsBox.Text = string.Join("\n", llm.FallbackModels);
        BuildFallbackModelsPanel();
        if (McpServersBox != null)
        {
            try
            {
                var json = System.Text.Json.JsonSerializer.Serialize(llm.McpServers,
                    new System.Text.Json.JsonSerializerOptions { WriteIndented = true,
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
                McpServersBox.Text = json;
            }
            catch (Exception) { McpServersBox.Text = "[]"; }
        }
        BuildMcpServerCards();
        BuildHookCards();
    }

    private void SaveAdvancedSettings()
    {
        var llm = _vm.Service.Settings.Llm;
        if (FallbackModelsBox != null)
        {
            llm.FallbackModels = FallbackModelsBox.Text
                .Split('\n', StringSplitOptions.RemoveEmptyEntries)
                .Select(s => s.Trim())
                .Where(s => s.Length > 0)
                .ToList();
        }
        if (McpServersBox != null && !string.IsNullOrWhiteSpace(McpServersBox.Text))
        {
            try
            {
                llm.McpServers = System.Text.Json.JsonSerializer.Deserialize<List<Models.McpServerEntry>>(
                    McpServersBox.Text) ?? new();
            }
            catch (Exception) { /* JSON 파싱 실패 시 기존 유지 */ }
        }

        // 도구 비활성 목록 저장
        if (_toolCardsLoaded)
            llm.DisabledTools = _disabledTools.ToList();
    }
}
