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;

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 카테고리 변경 팝업 ──────────────────────────────────────────────

    private void ShowConversationMenu(string conversationId)
    {
        var conv = _storage.Load(conversationId);
        var isPinned = conv?.Pinned ?? false;

        var primaryText = ThemeResourceHelper.Primary(this);
        var secondaryText = ThemeResourceHelper.Secondary(this);
        var hoverBg = ThemeResourceHelper.HoverBg(this);

        var (popup, stack) = PopupMenuHelper.Create(this, this, PlacementMode.MousePoint, minWidth: 200);

        // 메뉴 항목 헬퍼 — PopupMenuHelper.MenuItem 래핑 (아이콘 색상 개별 지정)
        Border CreateMenuItem(string icon, string text, Brush iconColor, Action onClick)
            => PopupMenuHelper.MenuItem(text, primaryText, hoverBg,
                () => { popup.IsOpen = false; onClick(); },
                icon: icon, iconColor: iconColor, fontSize: 12.5);

        Border CreateSeparator() => PopupMenuHelper.Separator();

        // 고정/해제
        stack.Children.Add(CreateMenuItem(
            isPinned ? "\uE77A" : "\uE718",
            isPinned ? "고정 해제" : "상단 고정",
            ThemeResourceHelper.Accent(this),
            () =>
            {
                var c = _storage.Load(conversationId);
                if (c != null)
                {
                    c.Pinned = !c.Pinned;
                    _storage.Save(c);
                    lock (_convLock) { if (_currentConversation?.Id == conversationId) _currentConversation.Pinned = c.Pinned; }
                    RefreshConversationList();
                }
            }));

        // 이름 변경
        stack.Children.Add(CreateMenuItem("\uE8AC", "이름 변경", secondaryText, () =>
        {
            // 대화 목록에서 해당 항목 찾아서 편집 모드 진입
            foreach (UIElement child in ConversationPanel.Children)
            {
                if (child is Border b && b.Child is Grid g)
                {
                    foreach (UIElement gc in g.Children)
                    {
                        if (gc is StackPanel sp && sp.Children.Count > 0 && sp.Children[0] is TextBlock tb)
                        {
                            // title과 매칭
                            if (conv != null && tb.Text == conv.Title)
                            {
                                var titleColor = ThemeResourceHelper.Primary(this);
                                EnterTitleEditMode(tb, conversationId, titleColor);
                                return;
                            }
                        }
                    }
                }
            }
        }));

        // Cowork/Code 탭: 작업 유형 읽기 전용 표시
        if ((_activeTab == "Cowork" || _activeTab == "Code") && conv != null)
        {
            var catKey = conv.Category ?? ChatCategory.General;
            // ChatCategory 또는 프리셋에서 아이콘/라벨 검색
            string catSymbol = "\uE8BD", catLabel = catKey, catColor = "#6B7280";
            var chatCat = ChatCategory.All.FirstOrDefault(c => c.Key == catKey);
            if (chatCat != default && chatCat.Key != ChatCategory.General)
            {
                catSymbol = chatCat.Symbol; catLabel = chatCat.Label; catColor = chatCat.Color;
            }
            else
            {
                var preset = Services.PresetService.GetByTabWithCustom(_activeTab, Llm.CustomPresets)
                    .FirstOrDefault(p => p.Category == catKey);
                if (preset != null)
                {
                    catSymbol = preset.Symbol; catLabel = preset.Label; catColor = preset.Color;
                }
            }

            stack.Children.Add(CreateSeparator());
            var infoSp = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(10, 4, 10, 4) };
            try
            {
                var catBrush = ThemeResourceHelper.HexBrush(catColor);
                infoSp.Children.Add(new TextBlock
                {
                    Text = catSymbol, FontFamily = ThemeResourceHelper.SegoeMdl2,
                    FontSize = 12, Foreground = catBrush,
                    VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 6, 0),
                });
                infoSp.Children.Add(new TextBlock
                {
                    Text = catLabel, FontSize = 12, Foreground = primaryText,
                    VerticalAlignment = VerticalAlignment.Center,
                });
            }
            catch (Exception)
            {
                infoSp.Children.Add(new TextBlock { Text = catLabel, FontSize = 12, Foreground = primaryText });
            }
            stack.Children.Add(infoSp);
        }

        // Chat 탭만 분류 변경 표시 (Cowork/Code 탭은 분류 불필요)
        var showCategorySection = _activeTab == "Chat";

        if (showCategorySection)
        {
            stack.Children.Add(CreateSeparator());

            // 분류 헤더
            stack.Children.Add(new TextBlock
            {
                Text = "분류 변경",
                FontSize = 10.5,
                Foreground = secondaryText,
                Margin = new Thickness(10, 4, 0, 4),
                FontWeight = FontWeights.SemiBold,
            });

            var currentCategory = conv?.Category ?? ChatCategory.General;
            var accentBrush = ThemeResourceHelper.Accent(this);

            foreach (var (key, label, symbol, color) in ChatCategory.All)
            {
                var capturedKey = key;
                var isCurrentCat = capturedKey == currentCategory;

                // 카테고리 항목 (체크 표시 포함)
                var catItem = new Border
                {
                    Background = Brushes.Transparent,
                    CornerRadius = new CornerRadius(8),
                    Padding = new Thickness(10, 7, 10, 7),
                    Margin = new Thickness(0, 1, 0, 1),
                    Cursor = Cursors.Hand,
                };
                var catGrid = new Grid();
                catGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(24) });
                catGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                catGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(20) });

                var catIcon = new TextBlock
                {
                    Text = symbol, FontFamily = ThemeResourceHelper.SegoeMdl2,
                    FontSize = 12, Foreground = BrushFromHex(color), VerticalAlignment = VerticalAlignment.Center,
                };
                Grid.SetColumn(catIcon, 0);
                catGrid.Children.Add(catIcon);

                var catText = new TextBlock
                {
                    Text = label, FontSize = 12.5, Foreground = primaryText,
                    VerticalAlignment = VerticalAlignment.Center,
                    FontWeight = isCurrentCat ? FontWeights.Bold : FontWeights.Normal,
                };
                Grid.SetColumn(catText, 1);
                catGrid.Children.Add(catText);

                if (isCurrentCat)
                {
                    var check = CreateSimpleCheck(accentBrush, 14);
                    Grid.SetColumn(check, 2);
                    catGrid.Children.Add(check);
                }

                catItem.Child = catGrid;
                catItem.MouseEnter += (s, _) => { if (s is Border b) b.Background = hoverBg; };
                catItem.MouseLeave += (s, _) => { if (s is Border b) b.Background = Brushes.Transparent; };
                catItem.MouseLeftButtonUp += (_, _) =>
                {
                    popup.IsOpen = false;
                    var c = _storage.Load(conversationId);
                    if (c != null)
                    {
                        c.Category = capturedKey;
                        var preset = Services.PresetService.GetByCategory(capturedKey);
                        if (preset != null)
                            c.SystemCommand = preset.SystemPrompt;
                        _storage.Save(c);
                        lock (_convLock)
                        {
                            if (_currentConversation?.Id == conversationId)
                            {
                                _currentConversation.Category = capturedKey;
                                if (preset != null)
                                    _currentConversation.SystemCommand = preset.SystemPrompt;
                            }
                        }
                        // 현재 대화의 카테고리가 변경되면 입력 안내 문구도 갱신
                        bool isCurrent;
                        lock (_convLock) { isCurrent = _currentConversation?.Id == conversationId; }
                        if (isCurrent && preset != null && !string.IsNullOrEmpty(preset.Placeholder))
                        {
                            _promptCardPlaceholder = preset.Placeholder;
                            UpdateWatermarkVisibility();
                            if (string.IsNullOrEmpty(InputBox.Text))
                            {
                                InputWatermark.Text = preset.Placeholder;
                                InputWatermark.Visibility = Visibility.Visible;
                            }
                        }
                        else if (isCurrent)
                        {
                            ClearPromptCardPlaceholder();
                        }
                        RefreshConversationList();
                    }
                };
                stack.Children.Add(catItem);
            }
        } // end showCategorySection

        stack.Children.Add(CreateSeparator());

        // 삭제
        stack.Children.Add(CreateMenuItem("\uE74D", "이 대화 삭제", Brushes.IndianRed, () =>
        {
            var result = CustomMessageBox.Show("이 대화를 삭제하시겠습니까?", "대화 삭제",
                MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result != MessageBoxResult.Yes) return;
            _storage.Delete(conversationId);
            lock (_convLock)
            {
                if (_currentConversation?.Id == conversationId)
                {
                    _currentConversation = null;
                    MessagePanel.Children.Clear();
                    EmptyState.Visibility = Visibility.Visible;
                    UpdateChatTitle();
                }
            }
            RefreshConversationList();
        }));

        popup.IsOpen = true;
    }
}
