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

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 대화 주제 버튼 ──────────────────────────────────────────────────

    /// <summary>프리셋에서 대화 주제 버튼을 동적으로 생성합니다.</summary>
    private void BuildTopicButtons()
    {
        TopicButtonPanel.Children.Clear();

        TopicButtonPanel.Visibility = Visibility.Visible;

        // 탭별 EmptyState 텍스트
        if (_activeTab == "Cowork" || _activeTab == "Code")
        {
            if (EmptyStateTitle != null) EmptyStateTitle.Text = "작업 유형을 선택하세요";
            if (EmptyStateDesc != null) EmptyStateDesc.Text = _activeTab == "Code"
                ? "코딩 에이전트가 코드 분석, 수정, 빌드, 테스트를 수행합니다"
                : "에이전트가 상세한 데이터를 작성합니다";
        }
        else
        {
            if (EmptyStateTitle != null) EmptyStateTitle.Text = "대화 주제를 선택하세요";
            if (EmptyStateDesc != null) EmptyStateDesc.Text = "주제에 맞는 전문 프리셋이 자동 적용됩니다";
        }

        var presets = Services.PresetService.GetByTabWithCustom(_activeTab, Llm.CustomPresets);

        foreach (var preset in presets)
        {
            var capturedPreset = preset;
            var btnColor = BrushFromHex(preset.Color);

            var border = new Border
            {
                Background = ThemeResourceHelper.ItemBg(this),
                CornerRadius = new CornerRadius(14),
                Padding = new Thickness(14, 12, 14, 12),
                Margin = new Thickness(4, 4, 4, 8),
                Cursor = Cursors.Hand,
                Width = 120,
                Height = 105,
                ClipToBounds = true,
                RenderTransformOrigin = new Point(0.5, 0.5),
                RenderTransform = new ScaleTransform(1, 1),
            };

            var stack = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center };

            // 아이콘 컨테이너 (원형 배경 + 펄스 애니메이션)
            var iconCircle = new Border
            {
                Width = 40, Height = 40,
                CornerRadius = new CornerRadius(20),
                Background = new SolidColorBrush(((SolidColorBrush)btnColor).Color) { Opacity = 0.15 },
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 0, 0, 10),
            };
            var iconTb = new TextBlock
            {
                Text = preset.Symbol,
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 18,
                Foreground = btnColor,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
            };
            iconCircle.Child = iconTb;
            stack.Children.Add(iconCircle);

            // 제목
            stack.Children.Add(new TextBlock
            {
                Text = preset.Label,
                FontSize = 13, FontWeight = FontWeights.SemiBold,
                Foreground = ThemeResourceHelper.Primary(this),
                HorizontalAlignment = HorizontalAlignment.Center,
            });

            // 설명
            stack.Children.Add(new TextBlock
            {
                Text = preset.Description,
                FontSize = 9, TextWrapping = TextWrapping.Wrap,
                TextTrimming = TextTrimming.CharacterEllipsis,
                MaxHeight = 28,
                Foreground = ThemeResourceHelper.Secondary(this),
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 2, 0, 0),
                TextAlignment = TextAlignment.Center,
            });

            // 커스텀 프리셋: 좌측 상단 뱃지
            if (capturedPreset.IsCustom)
            {
                var grid = new Grid();
                grid.Children.Add(stack);
                var badge = new Border
                {
                    Width = 16, Height = 16,
                    CornerRadius = new CornerRadius(4),
                    Background = new SolidColorBrush(Color.FromArgb(0x60, 0xFF, 0xFF, 0xFF)),
                    HorizontalAlignment = HorizontalAlignment.Left,
                    VerticalAlignment = VerticalAlignment.Top,
                    Margin = new Thickness(2, 2, 0, 0),
                    ToolTip = "커스텀 프리셋",
                };
                badge.Child = new TextBlock
                {
                    Text = "\uE710", // + 아이콘
                    FontFamily = ThemeResourceHelper.SegoeMdl2,
                    FontSize = 8,
                    Foreground = btnColor,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                };
                grid.Children.Add(badge);
                border.Child = grid;
            }
            else
            {
                border.Child = stack;
            }

            // 호버 애니메이션 — 스케일 1.05x + 밝기 변경
            var hoverBg = ThemeResourceHelper.HoverBg(this);
            var normalBg = ThemeResourceHelper.ItemBg(this);
            border.MouseEnter += (s, _) =>
            {
                if (s is Border b && b.RenderTransform is ScaleTransform st)
                {
                    st.ScaleX = 1.03; st.ScaleY = 1.03;
                    b.Background = hoverBg;
                }
            };
            border.MouseLeave += (s, _) =>
            {
                if (s is Border b && b.RenderTransform is ScaleTransform st)
                {
                    st.ScaleX = 1.0; st.ScaleY = 1.0;
                    b.Background = normalBg;
                }
            };

            // 클릭 → 해당 주제로 새 대화 시작
            border.MouseLeftButtonDown += (_, _) => SelectTopic(capturedPreset);

            // 커스텀 프리셋: 우클릭 메뉴 (편집/삭제)
            if (capturedPreset.IsCustom)
            {
                border.MouseRightButtonUp += (s, e) =>
                {
                    e.Handled = true;
                    ShowCustomPresetContextMenu(s as Border, capturedPreset);
                };
            }

            TopicButtonPanel.Children.Add(border);
        }

        // "기타" 자유 입력 버튼 추가
        {
            var etcColor = BrushFromHex("#6B7280"); // 회색
            var etcBorder = new Border
            {
                Background = ThemeResourceHelper.ItemBg(this),
                CornerRadius = new CornerRadius(14),
                Padding = new Thickness(14, 12, 14, 12),
                Margin = new Thickness(4, 4, 4, 8),
                Cursor = Cursors.Hand,
                Width = 120,
                Height = 105,
                ClipToBounds = true,
                RenderTransformOrigin = new Point(0.5, 0.5),
                RenderTransform = new ScaleTransform(1, 1),
            };

            var etcStack = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center };

            var etcIconCircle = new Border
            {
                Width = 40, Height = 40,
                CornerRadius = new CornerRadius(20),
                Background = new SolidColorBrush(((SolidColorBrush)etcColor).Color) { Opacity = 0.15 },
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 0, 0, 10),
            };
            etcIconCircle.Child = new TextBlock
            {
                Text = "\uED25", // Edit 아이콘
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 18,
                Foreground = etcColor,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
            };
            etcStack.Children.Add(etcIconCircle);

            etcStack.Children.Add(new TextBlock
            {
                Text = "기타",
                FontSize = 13, FontWeight = FontWeights.SemiBold,
                Foreground = ThemeResourceHelper.Primary(this),
                HorizontalAlignment = HorizontalAlignment.Center,
            });
            etcStack.Children.Add(new TextBlock
            {
                Text = "프리셋 없이 자유롭게 대화합니다",
                FontSize = 9, TextWrapping = TextWrapping.Wrap,
                TextTrimming = TextTrimming.CharacterEllipsis,
                MaxHeight = 28,
                Foreground = ThemeResourceHelper.Secondary(this),
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 2, 0, 0),
                TextAlignment = TextAlignment.Center,
            });

            etcBorder.Child = etcStack;

            var hoverBg2 = ThemeResourceHelper.HoverBg(this);
            var normalBg2 = ThemeResourceHelper.ItemBg(this);
            etcBorder.MouseEnter += (s, _) =>
            {
                if (s is Border b && b.RenderTransform is ScaleTransform st)
                { st.ScaleX = 1.03; st.ScaleY = 1.03; b.Background = hoverBg2; }
            };
            etcBorder.MouseLeave += (s, _) =>
            {
                if (s is Border b && b.RenderTransform is ScaleTransform st)
                { st.ScaleX = 1.0; st.ScaleY = 1.0; b.Background = normalBg2; }
            };

            etcBorder.MouseLeftButtonDown += (_, _) =>
            {
                EmptyState.Visibility = Visibility.Collapsed;
                InputBox.Focus();
            };
            TopicButtonPanel.Children.Add(etcBorder);
        }

        // ── "+" 커스텀 프리셋 추가 버튼 ──
        {
            var addColor = BrushFromHex("#6366F1");
            var addBorder = new Border
            {
                Background = Brushes.Transparent,
                CornerRadius = new CornerRadius(14),
                Padding = new Thickness(14, 12, 14, 12),
                Margin = new Thickness(4, 4, 4, 8),
                Cursor = Cursors.Hand,
                Width = 120, Height = 105,
                ClipToBounds = true,
                BorderBrush = ThemeResourceHelper.Border(this),
                BorderThickness = new Thickness(1.5),
                RenderTransformOrigin = new Point(0.5, 0.5),
                RenderTransform = new ScaleTransform(1, 1),
            };
            // 점선 효과를 위한 Dashes
            if (addBorder.BorderBrush is SolidColorBrush scb)
            {
                var dashPen = new Pen(scb, 1.5) { DashStyle = DashStyles.Dash };
            }

            var addStack = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };

            // + 아이콘
            var plusIcon = new TextBlock
            {
                Text = "\uE710",
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 24,
                Foreground = ThemeResourceHelper.Secondary(this),
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 8, 0, 8),
            };
            addStack.Children.Add(plusIcon);

            addStack.Children.Add(new TextBlock
            {
                Text = "프리셋 추가",
                FontSize = 12,
                Foreground = ThemeResourceHelper.Secondary(this),
                HorizontalAlignment = HorizontalAlignment.Center,
            });

            addBorder.Child = addStack;

            var hoverBg3 = ThemeResourceHelper.HoverBg(this);
            addBorder.MouseEnter += (s, _) =>
            {
                if (s is Border b && b.RenderTransform is ScaleTransform st)
                { st.ScaleX = 1.03; st.ScaleY = 1.03; b.Background = hoverBg3; }
            };
            addBorder.MouseLeave += (s, _) =>
            {
                if (s is Border b && b.RenderTransform is ScaleTransform st)
                { st.ScaleX = 1.0; st.ScaleY = 1.0; b.Background = Brushes.Transparent; }
            };
            addBorder.MouseLeftButtonDown += (_, _) => ShowCustomPresetDialog();
            TopicButtonPanel.Children.Add(addBorder);
        }
    }
}
