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

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 에이전트 이벤트 배너 ─────────────────────────────────────────────

    private void AddAgentEventBanner(AgentEvent evt)
    {
        var logLevel = Llm.AgentLogLevel;

        // Planning 이벤트는 단계 목록 카드로 별도 렌더링
        if (evt.Type == AgentEventType.Planning && evt.Steps is { Count: > 0 })
        {
            AddPlanningCard(evt);
            return;
        }

        // StepStart 이벤트는 진행률 바 업데이트
        if (evt.Type == AgentEventType.StepStart && evt.StepTotal > 0)
        {
            UpdateProgressBar(evt);
            return;
        }

        // simple 모드: ToolCall은 건너뜀 (ToolResult만 한 줄로 표시)
        if (logLevel == "simple" && evt.Type == AgentEventType.ToolCall)
            return;

        // 전체 통계 이벤트는 별도 색상 (보라색 계열)
        var isTotalStats = evt.Type == AgentEventType.StepDone && evt.ToolName == "total_stats";

        var (icon, label, bgHex, fgHex) = isTotalStats
            ? ("\uE9D2", "Total Stats", "#F3EEFF", "#7C3AED")
            : evt.Type switch
            {
                AgentEventType.Thinking   => ("\uE8BD", "Thinking",   "#F0F0FF", "#6B7BC4"),
                AgentEventType.ToolCall   => ("\uE8A7", evt.ToolName, "#EEF6FF", "#3B82F6"),
                AgentEventType.ToolResult => ("\uE73E", evt.ToolName, "#EEF9EE", "#16A34A"),
                AgentEventType.SkillCall  => ("\uE8A5", evt.ToolName, "#FFF7ED", "#EA580C"),
                AgentEventType.Error      => ("\uE783", "Error",      "#FEF2F2", "#DC2626"),
                AgentEventType.Complete   => ("\uE930", "Complete",   "#F0FFF4", "#15803D"),
                AgentEventType.StepDone   => ("\uE73E", "Step Done",  "#EEF9EE", "#16A34A"),
                AgentEventType.Paused     => ("\uE769", "Paused",     "#FFFBEB", "#D97706"),
                AgentEventType.Resumed    => ("\uE768", "Resumed",    "#ECFDF5", "#059669"),
                _                         => ("\uE946", "Agent",      "#F5F5F5", "#6B7280"),
            };

        var banner = new Border
        {
            Background = ThemeResourceHelper.HexBrush(bgHex),
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(12, 8, 12, 8),
            Margin = new Thickness(40, 2, 40, 2),
            HorizontalAlignment = HorizontalAlignment.Stretch,
        };

        var sp = new StackPanel();

        // 헤더: Grid로 좌측(아이콘+라벨) / 우측(타이밍+토큰) 분리 고정
        var headerGrid = new Grid();
        headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        headerGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

        // 좌측: 아이콘 + 라벨
        var headerLeft = new StackPanel { Orientation = Orientation.Horizontal };
        headerLeft.Children.Add(new TextBlock
        {
            Text = icon,
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 11,
            Foreground = ThemeResourceHelper.HexBrush(fgHex),
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
        });
        headerLeft.Children.Add(new TextBlock
        {
            Text = label,
            FontSize = 11.5,
            FontWeight = FontWeights.SemiBold,
            Foreground = ThemeResourceHelper.HexBrush(fgHex),
            VerticalAlignment = VerticalAlignment.Center,
        });
        Grid.SetColumn(headerLeft, 0);

        // 우측: 소요 시간 + 토큰 배지 (항상 우측 끝에 고정)
        var headerRight = new StackPanel { Orientation = Orientation.Horizontal };
        if (logLevel != "simple" && evt.ElapsedMs > 0)
        {
            headerRight.Children.Add(new TextBlock
            {
                Text = evt.ElapsedMs < 1000 ? $"{evt.ElapsedMs}ms" : $"{evt.ElapsedMs / 1000.0:F1}s",
                FontSize = 10,
                Foreground = ThemeResourceHelper.HexBrush("#9CA3AF"),
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(8, 0, 0, 0),
            });
        }
        if (logLevel != "simple" && (evt.InputTokens > 0 || evt.OutputTokens > 0))
        {
            var tokenText = evt.InputTokens > 0 && evt.OutputTokens > 0
                ? $"{evt.InputTokens}→{evt.OutputTokens}t"
                : evt.InputTokens > 0 ? $"↑{evt.InputTokens}t" : $"↓{evt.OutputTokens}t";
            headerRight.Children.Add(new Border
            {
                Background = ThemeResourceHelper.HexBrush("#F0F0F5"),
                CornerRadius = new CornerRadius(4),
                Padding = new Thickness(5, 1, 5, 1),
                Margin = new Thickness(6, 0, 0, 0),
                VerticalAlignment = VerticalAlignment.Center,
                Child = new TextBlock
                {
                    Text = tokenText,
                    FontSize = 9.5,
                    Foreground = ThemeResourceHelper.HexBrush("#8B8FA3"),
                    FontFamily = ThemeResourceHelper.Consolas,
                },
            });
        }
        Grid.SetColumn(headerRight, 1);

        headerGrid.Children.Add(headerLeft);
        headerGrid.Children.Add(headerRight);

        // header 변수를 headerLeft로 설정 (이후 expandIcon 추가 시 사용)
        var header = headerLeft;

        sp.Children.Add(headerGrid);

        // simple 모드: 요약 한 줄만 표시 (접기 없음)
        if (logLevel == "simple")
        {
            if (!string.IsNullOrEmpty(evt.Summary))
            {
                var shortSummary = evt.Summary.Length > 100
                    ? evt.Summary[..100] + "…"
                    : evt.Summary;
                sp.Children.Add(new TextBlock
                {
                    Text = shortSummary,
                    FontSize = 11,
                    Foreground = ThemeResourceHelper.HexBrush("#6B7280"),
                    TextWrapping = TextWrapping.NoWrap,
                    TextTrimming = TextTrimming.CharacterEllipsis,
                    Margin = new Thickness(0, 2, 0, 0),
                });
            }
        }
        // detailed/debug 모드: 기존 접이식 표시
        else if (!string.IsNullOrEmpty(evt.Summary))
        {
            var summaryText = evt.Summary;
            var isExpandable = (evt.Type == AgentEventType.ToolCall || evt.Type == AgentEventType.ToolResult)
                               && summaryText.Length > 60;

            if (isExpandable)
            {
                // 첫 줄만 표시하고 클릭하면 전체 내용 펼침
                var shortText = summaryText.Length > 80 ? summaryText[..80] + "..." : summaryText;
                var summaryTb = new TextBlock
                {
                    Text = shortText,
                    FontSize = 11.5,
                    Foreground = ThemeResourceHelper.HexBrush("#4B5563"),
                    TextWrapping = TextWrapping.Wrap,
                    Margin = new Thickness(0, 3, 0, 0),
                    Cursor = Cursors.Hand,
                };

                // Diff가 포함된 경우 색상 하이라이팅 적용
                var hasDiff = summaryText.Contains("--- ") && summaryText.Contains("+++ ");
                UIElement fullContent;

                if (hasDiff)
                {
                    fullContent = BuildDiffView(summaryText);
                }
                else
                {
                    fullContent = new TextBlock
                    {
                        Text = summaryText,
                        FontSize = 11,
                        Foreground = ThemeResourceHelper.HexBrush("#6B7280"),
                        TextWrapping = TextWrapping.Wrap,
                        FontFamily = ThemeResourceHelper.Consolas,
                    };
                }
                fullContent.Visibility = Visibility.Collapsed;
                ((FrameworkElement)fullContent).Margin = new Thickness(0, 4, 0, 0);

                // 펼침/접기 토글
                var expandIcon = new TextBlock
                {
                    Text = "\uE70D", // ChevronDown
                    FontFamily = ThemeResourceHelper.SegoeMdl2,
                    FontSize = 9,
                    Foreground = ThemeResourceHelper.HexBrush("#9CA3AF"),
                    Margin = new Thickness(6, 0, 0, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                };
                header.Children.Add(expandIcon);

                var isExpanded = false;
                banner.MouseLeftButtonDown += (_, _) =>
                {
                    isExpanded = !isExpanded;
                    fullContent.Visibility = isExpanded ? Visibility.Visible : Visibility.Collapsed;
                    summaryTb.Visibility = isExpanded ? Visibility.Collapsed : Visibility.Visible;
                    expandIcon.Text = isExpanded ? "\uE70E" : "\uE70D"; // ChevronUp : ChevronDown
                };

                sp.Children.Add(summaryTb);
                sp.Children.Add(fullContent);
            }
            else
            {
                sp.Children.Add(new TextBlock
                {
                    Text = summaryText,
                    FontSize = 11.5,
                    Foreground = ThemeResourceHelper.HexBrush("#4B5563"),
                    TextWrapping = TextWrapping.Wrap,
                    Margin = new Thickness(0, 3, 0, 0),
                });
            }
        }

        // debug 모드: ToolInput 파라미터 표시
        if (logLevel == "debug" && !string.IsNullOrEmpty(evt.ToolInput))
        {
            sp.Children.Add(new Border
            {
                Background = ThemeResourceHelper.HexBrush("#F8F8FC"),
                CornerRadius = new CornerRadius(4),
                Padding = new Thickness(8, 4, 8, 4),
                Margin = new Thickness(0, 4, 0, 0),
                Child = new TextBlock
                {
                    Text = evt.ToolInput.Length > 500 ? evt.ToolInput[..500] + "…" : evt.ToolInput,
                    FontSize = 10,
                    Foreground = ThemeResourceHelper.HexBrush("#7C7F93"),
                    FontFamily = ThemeResourceHelper.Consolas,
                    TextWrapping = TextWrapping.Wrap,
                },
            });
        }

        // 파일 경로 배너 (Claude 스타일)
        if (!string.IsNullOrEmpty(evt.FilePath))
        {
            var pathBorder = new Border
            {
                Background = ThemeResourceHelper.HexBrush("#F8FAFC"),
                CornerRadius = new CornerRadius(4),
                Padding = new Thickness(8, 4, 8, 4),
                Margin = new Thickness(0, 4, 0, 0),
            };
            var pathPanel = new StackPanel { Orientation = Orientation.Horizontal };
            pathPanel.Children.Add(new TextBlock
            {
                Text = "\uE8B7", // folder icon
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 10,
                Foreground = ThemeResourceHelper.HexBrush("#9CA3AF"),
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 4, 0),
            });
            pathPanel.Children.Add(new TextBlock
            {
                Text = evt.FilePath,
                FontSize = 10.5,
                Foreground = ThemeResourceHelper.HexBrush("#6B7280"),
                FontFamily = ThemeResourceHelper.Consolas,
                VerticalAlignment = VerticalAlignment.Center,
                TextTrimming = TextTrimming.CharacterEllipsis,
            });

            // 빠른 작업 버튼들
            var quickActions = BuildFileQuickActions(evt.FilePath);
            pathPanel.Children.Add(quickActions);

            pathBorder.Child = pathPanel;
            sp.Children.Add(pathBorder);
        }

        banner.Child = sp;

        // Total Stats 배너 클릭 → 워크플로우 분석기 병목 분석 탭 열기
        if (isTotalStats)
        {
            banner.Cursor = Cursors.Hand;
            banner.ToolTip = "클릭하여 병목 분석 보기";
            banner.MouseLeftButtonUp += (_, _) =>
            {
                OpenWorkflowAnalyzerIfEnabled();
                _analyzerWindow?.SwitchToBottleneckTab();
                _analyzerWindow?.Activate();
            };
        }

        // 페이드인 애니메이션
        banner.Opacity = 0;
        banner.BeginAnimation(UIElement.OpacityProperty,
            new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(200)));

        MessagePanel.Children.Add(banner);
    }

    /// <summary>파일 빠른 작업 버튼 패널을 생성합니다.</summary>
    private StackPanel BuildFileQuickActions(string filePath)
    {
        var panel = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Margin = new Thickness(6, 0, 0, 0),
            VerticalAlignment = VerticalAlignment.Center,
        };

        var accentColor = ThemeResourceHelper.HexColor("#3B82F6");
        var accentBrush = new SolidColorBrush(accentColor);

        Border MakeBtn(string mdlIcon, string label, Action action)
        {
            var sp = new StackPanel { Orientation = Orientation.Horizontal };
            sp.Children.Add(new TextBlock
            {
                Text = mdlIcon,
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 9,
                Foreground = accentBrush,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 3, 0),
            });
            sp.Children.Add(new TextBlock
            {
                Text = label,
                FontSize = 10,
                Foreground = accentBrush,
                VerticalAlignment = VerticalAlignment.Center,
            });
            var btn = new Border
            {
                Child = sp,
                Background = Brushes.Transparent,
                CornerRadius = new CornerRadius(4),
                Padding = new Thickness(5, 2, 5, 2),
                Cursor = Cursors.Hand,
            };
            btn.MouseEnter += (s, _) => { if (s is Border b) b.Background = new SolidColorBrush(Color.FromArgb(0x15, 0x3B, 0x82, 0xF6)); };
            btn.MouseLeave += (s, _) => { if (s is Border b) b.Background = Brushes.Transparent; };
            btn.MouseLeftButtonUp += (_, _) => action();
            return btn;
        }

        // 프리뷰 (지원 확장자만)
        var ext = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
        if (_previewableExtensions.Contains(ext))
        {
            var path1 = filePath;
            panel.Children.Add(MakeBtn("\uE8A1", "프리뷰", () => ShowPreviewPanel(path1)));
        }

        // 외부 열기
        var path2 = filePath;
        panel.Children.Add(MakeBtn("\uE8A7", "열기", () =>
        {
            try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo { FileName = path2, UseShellExecute = true }); } catch (Exception) { /* 파일 열기 실패 */ }
        }));

        // 폴더 열기
        var path3 = filePath;
        panel.Children.Add(MakeBtn("\uED25", "폴더", () =>
        {
            try { System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{path3}\""); } catch (Exception) { /* 탐색기 열기 실패 */ }
        }));

        // 경로 복사
        var path4 = filePath;
        panel.Children.Add(MakeBtn("\uE8C8", "복사", () =>
        {
            try
            {
                Clipboard.SetText(path4);
                // 1.5초 피드백: "복사됨" 표시
                if (panel.Children[^1] is Border lastBtn && lastBtn.Child is StackPanel lastSp)
                {
                    var origLabel = lastSp.Children.OfType<TextBlock>().LastOrDefault();
                    if (origLabel != null)
                    {
                        var prev = origLabel.Text;
                        origLabel.Text = "복사됨 ✓";
                        var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1500) };
                        timer.Tick += (_, _) => { origLabel.Text = prev; timer.Stop(); };
                        timer.Start();
                    }
                }
            }
            catch (Exception) { /* 비핵심 작업 실패 — UI 차단 방지 */ }
        }));

        return panel;
    }
}
