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.Models;
using AxCopilot.Services;

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 메시지 렌더링 ───────────────────────────────────────────────────

    private void RenderMessages()
    {
        MessagePanel.Children.Clear();

        ChatConversation? conv;
        lock (_convLock) conv = _currentConversation;

        if (conv == null || conv.Messages.Count == 0)
        {
            EmptyState.Visibility = Visibility.Visible;
            return;
        }

        EmptyState.Visibility = Visibility.Collapsed;

        foreach (var msg in conv.Messages)
        {
            if (msg.Role == "system") continue;
            AddMessageBubble(msg.Role, msg.Content, animate: false, message: msg);
        }

        _ = Dispatcher.InvokeAsync(() => MessageScroll.ScrollToEnd(), DispatcherPriority.Background);
    }

    private void AddMessageBubble(string role, string content, bool animate = true, ChatMessage? message = null)
    {
        var isUser = role == "user";

        if (isUser)
        {
            // 사용자: 우측 정렬, 악센트 배경 + 편집 버튼
            var wrapper = new StackPanel
            {
                HorizontalAlignment = HorizontalAlignment.Right,
                MaxWidth = 540,
                Margin = new Thickness(120, 6, 40, 6),
            };

            var bubble = new Border
            {
                Background = ThemeResourceHelper.Accent(this),
                CornerRadius = new CornerRadius(16, 4, 16, 16),
                Padding = new Thickness(16, 10, 16, 10),
                Child = new TextBlock
                {
                    Text = content,
                    FontSize = 13.5,
                    Foreground = Brushes.White,
                    TextWrapping = TextWrapping.Wrap,
                    LineHeight = 21,
                }
            };
            wrapper.Children.Add(bubble);

            // 액션 버튼 바 (복사 + 편집, hover 시 표시)
            var userActionBar = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Right,
                Opacity = 0,
                Margin = new Thickness(0, 2, 0, 0),
            };
            var capturedUserContent = content;
            var userBtnColor = ThemeResourceHelper.Secondary(this);
            userActionBar.Children.Add(CreateActionButton("\uE8C8", "복사", userBtnColor, () =>
            {
                try { Clipboard.SetText(capturedUserContent); } catch (Exception) { /* 클립보드 접근 실패 */ }
            }));
            userActionBar.Children.Add(CreateActionButton("\uE70F", "편집", userBtnColor,
                () => EnterEditMode(wrapper, capturedUserContent)));

            // 타임스탬프 + 액션 바
            var userBottomBar = new Grid { Margin = new Thickness(0, 2, 0, 0) };
            var timestamp = message?.Timestamp ?? DateTime.Now;
            userBottomBar.Children.Add(new TextBlock
            {
                Text = timestamp.ToString("HH:mm"),
                FontSize = 10, Opacity = 0.5,
                Foreground = ThemeResourceHelper.Secondary(this),
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 4, 0),
            });
            userBottomBar.Children.Add(userActionBar);
            wrapper.Children.Add(userBottomBar);
            wrapper.MouseEnter += (_, _) => userActionBar.Opacity = 1;
            wrapper.MouseLeave += (_, _) => userActionBar.Opacity = 0;

            // 우클릭 → 메시지 컨텍스트 메뉴
            var userContent = content;
            wrapper.MouseRightButtonUp += (_, re) =>
            {
                re.Handled = true;
                ShowMessageContextMenu(userContent, "user");
            };

            if (animate) ApplyMessageEntryAnimation(wrapper);
            MessagePanel.Children.Add(wrapper);
        }
        else
        {
            // 어시스턴트: 좌측 정렬, 다크 배경
            var container = new StackPanel
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                MaxWidth = GetMessageMaxWidth(),
                Margin = new Thickness(40, 8, 80, 8)
            };
            if (animate) ApplyMessageEntryAnimation(container);

            // AI 에이전트 이름 + 아이콘
            var (agentName, agentSymbol, agentColor) = GetAgentIdentity();
            var agentBrush = BrushFromHex(agentColor);
            var headerSp = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 4) };

            // 다이아몬드 심볼 아이콘 (회전 애니메이션)
            var iconBlock = new TextBlock
            {
                Text = "◆",
                FontSize = 13,
                Foreground = agentBrush,
                VerticalAlignment = VerticalAlignment.Center,
                RenderTransformOrigin = new Point(0.5, 0.5),
                RenderTransform = new RotateTransform(0),
            };
            if (animate)
            {
                var spin = new System.Windows.Media.Animation.DoubleAnimation
                {
                    From = 0, To = 360,
                    Duration = TimeSpan.FromSeconds(1.2),
                    EasingFunction = new System.Windows.Media.Animation.CubicEase { EasingMode = System.Windows.Media.Animation.EasingMode.EaseOut },
                };
                ((RotateTransform)iconBlock.RenderTransform).BeginAnimation(RotateTransform.AngleProperty, spin);
            }
            headerSp.Children.Add(iconBlock);

            headerSp.Children.Add(new TextBlock
            {
                Text = agentName,
                FontSize = 11,
                FontWeight = FontWeights.SemiBold,
                Foreground = agentBrush,
                Margin = new Thickness(6, 0, 0, 0),
                VerticalAlignment = VerticalAlignment.Center,
            });
            container.Children.Add(headerSp);

            // 마크다운 렌더링 (파일 경로 강조 설정 연동)
            MarkdownRenderer.EnableFilePathHighlight =
                Llm.EnableFilePathHighlight;
            var primaryText = ThemeResourceHelper.Primary(this);
            var secondaryText = ThemeResourceHelper.Secondary(this);
            var accentBrush = ThemeResourceHelper.Accent(this);
            var codeBgBrush = ThemeResourceHelper.Hint(this);
            var mdPanel = MarkdownRenderer.Render(content, primaryText, secondaryText, accentBrush, codeBgBrush);
            mdPanel.Margin = new Thickness(0, 0, 0, 4);
            container.Children.Add(mdPanel);

            // 액션 버튼 바 (복사 / 좋아요 / 싫어요)
            var actionBar = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = new Thickness(0, 6, 0, 0)
            };

            var btnColor = (ThemeResourceHelper.Secondary(this));
            var btnHoverColor = new SolidColorBrush(Color.FromRgb(0x8B, 0x90, 0xB0));
            var capturedContent = content;

            actionBar.Children.Add(CreateActionButton("\uE8C8", "복사", btnColor, () =>
            {
                try { Clipboard.SetText(capturedContent); } catch (Exception) { /* 클립보드 접근 실패 */ }
            }));
            actionBar.Children.Add(CreateActionButton("\uE72C", "다시 생성", btnColor, () => _ = RegenerateLastAsync()));
            actionBar.Children.Add(CreateActionButton("\uE70F", "수정 후 재시도", btnColor, () => ShowRetryWithFeedbackInput()));
            AddLinkedFeedbackButtons(actionBar, btnColor, message);

            // 타임스탬프
            var aiTimestamp = message?.Timestamp ?? DateTime.Now;
            actionBar.Children.Add(new TextBlock
            {
                Text = aiTimestamp.ToString("HH:mm"),
                FontSize = 10, Opacity = 0.5,
                Foreground = btnColor,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(8, 0, 0, 0),
            });

            container.Children.Add(actionBar);

            // 우클릭 → 메시지 컨텍스트 메뉴
            var aiContent = content;
            container.MouseRightButtonUp += (_, re) =>
            {
                re.Handled = true;
                ShowMessageContextMenu(aiContent, "assistant");
            };

            MessagePanel.Children.Add(container);
        }
    }

}
