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

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 무드 메뉴 / 플레이스홀더 / 설정 패널 ────────────────────────────

    private string? _promptCardPlaceholder;

    /// <summary>포맷 선택 팝업 메뉴를 표시합니다.</summary>
    private void ShowFormatMenu()
    {
        FormatMenuItems.Children.Clear();

        var primaryText = ThemeResourceHelper.Primary(this);
        var secondaryText = ThemeResourceHelper.Secondary(this);
        var accentBrush = ThemeResourceHelper.Accent(this);
        var currentFormat = Llm.DefaultOutputFormat ?? "auto";

        var formats = new (string Key, string Label, string Icon, string Color)[]
        {
            ("auto", "AI 자동 선택", "\uE8BD", "#8B5CF6"),
            ("xlsx", "Excel", "\uE9F9", "#217346"),
            ("html", "HTML 보고서", "\uE12B", "#E44D26"),
            ("docx", "Word", "\uE8A5", "#2B579A"),
            ("md", "Markdown", "\uE943", "#6B7280"),
            ("csv", "CSV", "\uE9D9", "#10B981"),
        };

        foreach (var (key, label, icon, color) in formats)
        {
            var isActive = key == currentFormat;
            var sp = new StackPanel { Orientation = Orientation.Horizontal };

            // 커스텀 체크 아이콘
            sp.Children.Add(CreateCheckIcon(isActive, accentBrush));

            sp.Children.Add(new TextBlock
            {
                Text = icon,
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 13,
                Foreground = BrushFromHex(color),
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 8, 0),
            });

            sp.Children.Add(new TextBlock
            {
                Text = label, FontSize = 13,
                Foreground = primaryText,
                VerticalAlignment = VerticalAlignment.Center,
            });

            var itemBorder = new Border
            {
                Child = sp,
                Background = Brushes.Transparent,
                CornerRadius = new CornerRadius(8),
                Cursor = Cursors.Hand,
                Padding = new Thickness(8, 7, 12, 7),
            };
            ApplyMenuItemHover(itemBorder);

            var capturedKey = key;
            itemBorder.MouseLeftButtonUp += (_, _) =>
            {
                FormatMenuPopup.IsOpen = false;
                Llm.DefaultOutputFormat = capturedKey;
                _settings.Save();
                BuildBottomBar();
            };

            FormatMenuItems.Children.Add(itemBorder);
        }

        // PlacementTarget을 동적 등록된 버튼으로 설정
        if (FindName("BtnFormatMenu") is UIElement formatTarget)
            FormatMenuPopup.PlacementTarget = formatTarget;
        FormatMenuPopup.IsOpen = true;
    }

    /// <summary>디자인 무드 선택 팝업 메뉴를 표시합니다.</summary>
    private void ShowMoodMenu()
    {
        MoodMenuItems.Children.Clear();

        var primaryText = ThemeResourceHelper.Primary(this);
        var secondaryText = ThemeResourceHelper.Secondary(this);
        var accentBrush = ThemeResourceHelper.Accent(this);
        var borderBrush = ThemeResourceHelper.Border(this);

        // 2열 갤러리 그리드
        var grid = new System.Windows.Controls.Primitives.UniformGrid { Columns = 2 };

        foreach (var mood in TemplateService.AllMoods)
        {
            var isActive = _selectedMood == mood.Key;
            var isCustom = Llm.CustomMoods.Any(cm => cm.Key == mood.Key);
            var colors = TemplateService.GetMoodColors(mood.Key);

            // 미니 프리뷰 카드
            var previewCard = new Border
            {
                Width = 160, Height = 80,
                CornerRadius = new CornerRadius(6),
                Background = ThemeResourceHelper.HexBrush(colors.Background),
                BorderBrush = isActive ? accentBrush : ThemeResourceHelper.HexBrush(colors.Border),
                BorderThickness = new Thickness(isActive ? 2 : 1),
                Padding = new Thickness(8, 6, 8, 6),
                Margin = new Thickness(2),
            };

            var previewContent = new StackPanel();
            // 헤딩 라인
            previewContent.Children.Add(new Border
            {
                Width = 60, Height = 6, CornerRadius = new CornerRadius(2),
                Background = ThemeResourceHelper.HexBrush(colors.PrimaryText),
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = new Thickness(0, 0, 0, 4),
            });
            // 악센트 라인
            previewContent.Children.Add(new Border
            {
                Width = 40, Height = 3, CornerRadius = new CornerRadius(1),
                Background = ThemeResourceHelper.HexBrush(colors.Accent),
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = new Thickness(0, 0, 0, 6),
            });
            // 텍스트 라인들
            for (int i = 0; i < 3; i++)
            {
                previewContent.Children.Add(new Border
                {
                    Width = 120 - i * 20, Height = 3, CornerRadius = new CornerRadius(1),
                    Background = new SolidColorBrush(ThemeResourceHelper.HexColor(colors.SecondaryText)) { Opacity = 0.5 },
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 0, 3),
                });
            }
            // 미니 카드 영역
            var cardRow = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 2, 0, 0) };
            for (int i = 0; i < 2; i++)
            {
                cardRow.Children.Add(new Border
                {
                    Width = 28, Height = 14, CornerRadius = new CornerRadius(2),
                    Background = ThemeResourceHelper.HexBrush(colors.CardBg),
                    BorderBrush = ThemeResourceHelper.HexBrush(colors.Border),
                    BorderThickness = new Thickness(0.5),
                    Margin = new Thickness(0, 0, 4, 0),
                });
            }
            previewContent.Children.Add(cardRow);
            previewCard.Child = previewContent;

            // 무드 라벨
            var labelPanel = new StackPanel { Margin = new Thickness(4, 2, 4, 4) };
            var labelRow = new StackPanel { Orientation = Orientation.Horizontal };
            labelRow.Children.Add(new TextBlock
            {
                Text = mood.Icon, FontSize = 12,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 4, 0),
            });
            labelRow.Children.Add(new TextBlock
            {
                Text = mood.Label, FontSize = 11.5,
                Foreground = primaryText,
                FontWeight = isActive ? FontWeights.SemiBold : FontWeights.Normal,
                VerticalAlignment = VerticalAlignment.Center,
            });
            if (isActive)
            {
                labelRow.Children.Add(new TextBlock
                {
                    Text = " ✓", FontSize = 11,
                    Foreground = accentBrush,
                    VerticalAlignment = VerticalAlignment.Center,
                });
            }
            labelPanel.Children.Add(labelRow);

            // 전체 카드 래퍼
            var cardWrapper = new Border
            {
                CornerRadius = new CornerRadius(8),
                Background = Brushes.Transparent,
                Cursor = Cursors.Hand,
                Padding = new Thickness(4),
                Margin = new Thickness(2),
            };
            var wrapperContent = new StackPanel();
            wrapperContent.Children.Add(previewCard);
            wrapperContent.Children.Add(labelPanel);
            cardWrapper.Child = wrapperContent;

            // 호버
            cardWrapper.MouseEnter += (s, _) => { if (s is Border b) b.Background = new SolidColorBrush(Color.FromArgb(0x12, 0xFF, 0xFF, 0xFF)); };
            cardWrapper.MouseLeave += (s, _) => { if (s is Border b) b.Background = Brushes.Transparent; };

            var capturedMood = mood;
            cardWrapper.MouseLeftButtonUp += (_, _) =>
            {
                MoodMenuPopup.IsOpen = false;
                _selectedMood = capturedMood.Key;
                Llm.DefaultMood = capturedMood.Key;
                _settings.Save();
                BuildBottomBar();
            };

            // 커스텀 무드: 우클릭
            if (isCustom)
            {
                cardWrapper.MouseRightButtonUp += (s, e) =>
                {
                    e.Handled = true;
                    MoodMenuPopup.IsOpen = false;
                    ShowCustomMoodContextMenu(s as Border, capturedMood.Key);
                };
            }

            grid.Children.Add(cardWrapper);
        }

        MoodMenuItems.Children.Add(grid);

        // ── 구분선 + 추가 버튼 ──
        MoodMenuItems.Children.Add(new System.Windows.Shapes.Rectangle
        {
            Height = 1,
            Fill = borderBrush,
            Margin = new Thickness(8, 4, 8, 4),
            Opacity = 0.4,
        });

        var addSp = new StackPanel { Orientation = Orientation.Horizontal };
        addSp.Children.Add(new TextBlock
        {
            Text = "\uE710",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 13,
            Foreground = secondaryText,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(4, 0, 8, 0),
        });
        addSp.Children.Add(new TextBlock
        {
            Text = "커스텀 무드 추가",
            FontSize = 13,
            Foreground = secondaryText,
            VerticalAlignment = VerticalAlignment.Center,
        });
        var addBorder = new Border
        {
            Child = addSp,
            Background = Brushes.Transparent,
            CornerRadius = new CornerRadius(8),
            Cursor = Cursors.Hand,
            Padding = new Thickness(8, 6, 12, 6),
        };
        ApplyMenuItemHover(addBorder);
        addBorder.MouseLeftButtonUp += (_, _) =>
        {
            MoodMenuPopup.IsOpen = false;
            ShowCustomMoodDialog();
        };
        MoodMenuItems.Children.Add(addBorder);

        if (FindName("BtnMoodMenu") is UIElement moodTarget)
            MoodMenuPopup.PlacementTarget = moodTarget;
        MoodMenuPopup.IsOpen = true;
    }

    /// <summary>커스텀 무드 추가/편집 다이얼로그를 표시합니다.</summary>
    private void ShowCustomMoodDialog(Models.CustomMoodEntry? existing = null)
    {
        bool isEdit = existing != null;
        var dlg = new CustomMoodDialog(
            existingKey: existing?.Key ?? "",
            existingLabel: existing?.Label ?? "",
            existingIcon: existing?.Icon ?? "🎯",
            existingDesc: existing?.Description ?? "",
            existingCss: existing?.Css ?? "")
        {
            Owner = this,
        };

        if (dlg.ShowDialog() == true)
        {
            if (isEdit)
            {
                existing!.Label = dlg.MoodLabel;
                existing.Icon = dlg.MoodIcon;
                existing.Description = dlg.MoodDescription;
                existing.Css = dlg.MoodCss;
            }
            else
            {
                Llm.CustomMoods.Add(new Models.CustomMoodEntry
                {
                    Key = dlg.MoodKey,
                    Label = dlg.MoodLabel,
                    Icon = dlg.MoodIcon,
                    Description = dlg.MoodDescription,
                    Css = dlg.MoodCss,
                });
            }
            _settings.Save();
            TemplateService.LoadCustomMoods(Llm.CustomMoods);
            BuildBottomBar();
        }
    }

    /// <summary>커스텀 무드 우클릭 컨텍스트 메뉴.</summary>
    private void ShowCustomMoodContextMenu(Border? anchor, string moodKey)
    {
        if (anchor == null) return;

        var popup = new System.Windows.Controls.Primitives.Popup
        {
            PlacementTarget = anchor,
            Placement = System.Windows.Controls.Primitives.PlacementMode.Right,
            StaysOpen = false, AllowsTransparency = true,
        };

        var menuBg = ThemeResourceHelper.Background(this);
        var primaryText = ThemeResourceHelper.Primary(this);
        var secondaryText = ThemeResourceHelper.Secondary(this);
        var borderBrush = ThemeResourceHelper.Border(this);

        var menuBorder = new Border
        {
            Background = menuBg,
            CornerRadius = new CornerRadius(10),
            BorderBrush = borderBrush,
            BorderThickness = new Thickness(1),
            Padding = new Thickness(4),
            MinWidth = 120,
            Effect = new System.Windows.Media.Effects.DropShadowEffect
            {
                BlurRadius = 12, ShadowDepth = 2, Opacity = 0.3, Color = Colors.Black,
            },
        };

        var stack = new StackPanel();

        var editItem = CreateContextMenuItem("\uE70F", "편집", primaryText, secondaryText);
        editItem.MouseLeftButtonDown += (_, _) =>
        {
            popup.IsOpen = false;
            var entry = Llm.CustomMoods.FirstOrDefault(c => c.Key == moodKey);
            if (entry != null) ShowCustomMoodDialog(entry);
        };
        stack.Children.Add(editItem);

        var deleteItem = CreateContextMenuItem("\uE74D", "삭제", new SolidColorBrush(Color.FromRgb(0xEF, 0x44, 0x44)), secondaryText);
        deleteItem.MouseLeftButtonDown += (_, _) =>
        {
            popup.IsOpen = false;
            var result = CustomMessageBox.Show(
                $"이 디자인 무드를 삭제하시겠습니까?",
                "무드 삭제", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                Llm.CustomMoods.RemoveAll(c => c.Key == moodKey);
                if (_selectedMood == moodKey) _selectedMood = "modern";
                _settings.Save();
                TemplateService.LoadCustomMoods(Llm.CustomMoods);
                BuildBottomBar();
            }
        };
        stack.Children.Add(deleteItem);

        menuBorder.Child = stack;
        popup.Child = menuBorder;
        popup.IsOpen = true;
    }

    private void ShowPlaceholder()
    {
        if (string.IsNullOrEmpty(_promptCardPlaceholder)) return;
        InputWatermark.Text = _promptCardPlaceholder;
        InputWatermark.Visibility = Visibility.Visible;
        InputBox.Text = "";
        InputBox.Focus();
    }

    private void UpdateWatermarkVisibility()
    {
        // 슬래시 칩이 활성화되어 있으면 워터마크 숨기기 (겹침 방지)
        if (_activeSlashCmd != null)
        {
            InputWatermark.Visibility = Visibility.Collapsed;
            return;
        }

        if (_promptCardPlaceholder != null && string.IsNullOrEmpty(InputBox.Text))
            InputWatermark.Visibility = Visibility.Visible;
        else
            InputWatermark.Visibility = Visibility.Collapsed;
    }

    private void ClearPromptCardPlaceholder()
    {
        _promptCardPlaceholder = null;
        InputWatermark.Visibility = Visibility.Collapsed;
    }

    private void BtnSettings_Click(object sender, RoutedEventArgs e)
    {
        // Phase 17-UI: 기어 버튼 → 인라인 설정 패널 토글
        // Ctrl+클릭 → 전역 SettingsWindow
        if (System.Windows.Input.Keyboard.Modifiers.HasFlag(System.Windows.Input.ModifierKeys.Control))
        {
            if (System.Windows.Application.Current is App app)
                app.OpenSettingsFromChat();
            return;
        }
        ToggleSettingsPanel();
    }

    /// <summary>Phase 32-E: 우측 설정 패널 슬라이드인/아웃 토글.</summary>
    private void ToggleSettingsPanel()
    {
        if (SettingsPanel.IsOpen)
        {
            SettingsPanel.IsOpen = false;
        }
        else
        {
            var activeTab = "Chat";
            if (TabCowork?.IsChecked == true) activeTab = "Cowork";
            else if (TabCode?.IsChecked == true) activeTab = "Code";

            SettingsPanel.LoadFromSettings(_settings, activeTab, _toolRegistry);
            SettingsPanel.CloseRequested -= OnSettingsPanelClose;
            SettingsPanel.CloseRequested += OnSettingsPanelClose;
            SettingsPanel.SettingsChanged -= OnSettingsPanelChanged;
            SettingsPanel.SettingsChanged += OnSettingsPanelChanged;
            // 콜백 연결 — ChatWindow 기존 구현에 위임
            SettingsPanel.ServiceSelectorRequested  = () => BtnModelSelector_Click(BtnModelSelector, new System.Windows.RoutedEventArgs());
            SettingsPanel.ModelSelectorRequested    = () => BtnModelSelector_Click(BtnModelSelector, new System.Windows.RoutedEventArgs());
            SettingsPanel.WorkFolderBrowseRequested = () => BrowseWorkFolder();
            SettingsPanel.PresetSaveRequested       = () => ShowCustomPresetDialog(null);
            SettingsPanel.PresetManageRequested     = () => ShowPresetManagePopup();
            SettingsPanel.IsOpen = true;
        }
    }

    private void OnSettingsPanelClose(object? sender, EventArgs e)
    {
        SettingsPanel.IsOpen = false;
    }

    /// <summary>Phase 17-UI: 설정 패널에서 설정 변경 시 ChatWindow UI를 갱신합니다.</summary>
    private void OnSettingsPanelChanged(object? sender, EventArgs e)
    {
        // 모델 라벨 갱신 — 설정 패널에서 모델/서비스 변경 가능성
        UpdateModelLabel();
        // 개발자 모드 변경 → 분석기 버튼 가시성 갱신
        UpdateAnalyzerButtonVisibility();
    }
}
