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

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── Task Decomposition UI ────────────────────────────────────────────

    // ════════════════════════════════════════════════════════════
    //  후속 작업 제안 칩 (suggest_actions)
    // ════════════════════════════════════════════════════════════

    /// <summary>suggest_actions 도구 결과를 클릭 가능한 칩으로 렌더링합니다.</summary>
    private void RenderSuggestActionChips(string jsonSummary)
    {
        // JSON에서 액션 목록 파싱 시도
        List<(string label, string command)> actions = new();
        try
        {
            // summary 형식: "label: command" 줄바꿈 구분 또는 JSON
            if (jsonSummary.Contains("\"label\""))
            {
                using var doc = System.Text.Json.JsonDocument.Parse(jsonSummary);
                if (doc.RootElement.ValueKind == System.Text.Json.JsonValueKind.Array)
                {
                    foreach (var item in doc.RootElement.EnumerateArray())
                    {
                        var label = item.TryGetProperty("label", out var l) ? l.GetString() ?? "" : "";
                        var cmd = item.TryGetProperty("command", out var c) ? c.GetString() ?? label : label;
                        if (!string.IsNullOrEmpty(label)) actions.Add((label, cmd));
                    }
                }
            }
            else
            {
                // 줄바꿈 형식: "1. label → command"
                foreach (var line in jsonSummary.Split('\n'))
                {
                    var trimmed = line.Trim().TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ' ');
                    if (string.IsNullOrEmpty(trimmed)) continue;
                    var parts = trimmed.Split('→', ':', '—');
                    if (parts.Length >= 2)
                        actions.Add((parts[0].Trim(), parts[1].Trim()));
                    else if (!string.IsNullOrEmpty(trimmed))
                        actions.Add((trimmed, trimmed));
                }
            }
        }
        catch (Exception) { return; }

        if (actions.Count == 0) return;

        var accentBrush = ThemeResourceHelper.Accent(this);
        var secondaryText = ThemeResourceHelper.Secondary(this);
        var hoverBg = ThemeResourceHelper.HoverBg(this);

        var container = new Border
        {
            Margin = new Thickness(40, 4, 40, 8),
            HorizontalAlignment = HorizontalAlignment.Stretch,
        };

        var headerStack = new StackPanel { Margin = new Thickness(0, 0, 0, 6) };
        headerStack.Children.Add(new TextBlock
        {
            Text = "💡 다음 작업 제안:",
            FontSize = 12,
            Foreground = secondaryText,
        });

        var chipPanel = new WrapPanel { Margin = new Thickness(0, 2, 0, 0) };

        foreach (var (label, command) in actions.Take(5))
        {
            var capturedCmd = command;
            var chip = new Border
            {
                CornerRadius = new CornerRadius(16),
                Padding = new Thickness(14, 7, 14, 7),
                Margin = new Thickness(0, 0, 8, 6),
                Cursor = Cursors.Hand,
                Background = new SolidColorBrush(Color.FromArgb(0x15,
                    ((SolidColorBrush)accentBrush).Color.R,
                    ((SolidColorBrush)accentBrush).Color.G,
                    ((SolidColorBrush)accentBrush).Color.B)),
                BorderBrush = new SolidColorBrush(Color.FromArgb(0x40,
                    ((SolidColorBrush)accentBrush).Color.R,
                    ((SolidColorBrush)accentBrush).Color.G,
                    ((SolidColorBrush)accentBrush).Color.B)),
                BorderThickness = new Thickness(1),
            };
            chip.Child = new TextBlock
            {
                Text = label,
                FontSize = 12.5,
                Foreground = accentBrush,
                FontWeight = FontWeights.SemiBold,
            };
            chip.MouseEnter += (s, _) => ((Border)s).Opacity = 0.8;
            chip.MouseLeave += (s, _) => ((Border)s).Opacity = 1.0;
            chip.MouseLeftButtonUp += (_, _) =>
            {
                // 칩 패널 제거 후 해당 명령 실행
                MessagePanel.Children.Remove(container);
                if (capturedCmd.StartsWith("/"))
                {
                    InputBox.Text = capturedCmd + " ";
                    InputBox.CaretIndex = InputBox.Text.Length;
                    InputBox.Focus();
                }
                else
                {
                    InputBox.Text = capturedCmd;
                    _ = SendMessageAsync();
                }
            };
            chipPanel.Children.Add(chip);
        }

        var outerStack = new StackPanel();
        outerStack.Children.Add(headerStack);
        outerStack.Children.Add(chipPanel);
        container.Child = outerStack;

        ApplyMessageEntryAnimation(container);
        MessagePanel.Children.Add(container);
        ForceScrollToEnd();
    }

    // ════════════════════════════════════════════════════════════
    //  피드백 학습 반영 (J)
    // ════════════════════════════════════════════════════════════

    /// <summary>최근 대화의 피드백(좋아요/싫어요)을 분석하여 선호도 요약을 반환합니다.</summary>
    private string BuildFeedbackContext()
    {
        try
        {
            var recentConversations = _storage.LoadAllMeta()
                .OrderByDescending(m => m.UpdatedAt)
                .Take(20)
                .ToList();

            var likedPatterns = new List<string>();
            var dislikedPatterns = new List<string>();

            foreach (var meta in recentConversations)
            {
                var conv = _storage.Load(meta.Id);
                if (conv == null) continue;

                foreach (var msg in conv.Messages.Where(m => m.Role == "assistant" && m.Feedback != null))
                {
                    // 첫 50자로 패턴 파악
                    var preview = msg.Content?.Length > 80 ? msg.Content[..80] : msg.Content ?? "";
                    if (msg.Feedback == "like")
                        likedPatterns.Add(preview);
                    else if (msg.Feedback == "dislike")
                        dislikedPatterns.Add(preview);
                }
            }

            if (likedPatterns.Count == 0 && dislikedPatterns.Count == 0)
                return "";

            var sb = new System.Text.StringBuilder();
            sb.AppendLine("\n[사용자 선호도 참고]");
            if (likedPatterns.Count > 0)
            {
                sb.AppendLine($"사용자가 좋아한 응답 스타일 ({likedPatterns.Count}건):");
                foreach (var p in likedPatterns.Take(5))
                    sb.AppendLine($"  - \"{p}...\"");
            }
            if (dislikedPatterns.Count > 0)
            {
                sb.AppendLine($"사용자가 싫어한 응답 스타일 ({dislikedPatterns.Count}건):");
                foreach (var p in dislikedPatterns.Take(5))
                    sb.AppendLine($"  - \"{p}...\"");
            }
            sb.AppendLine("위 선호도를 참고하여 응답 스타일을 조정하세요.");
            return sb.ToString();
        }
        catch (Exception) { return ""; }
    }

    /// <summary>진행률 바와 단계 상태를 업데이트합니다.</summary>
    private void UpdateProgressBar(AgentEvent evt)
    {
        if (_planProgressBar == null || _planStepsPanel == null || _planProgressText == null)
            return;

        var stepIdx = evt.StepCurrent - 1; // 0-based
        var total = evt.StepTotal;

        // 진행률 바 업데이트
        _planProgressBar.Value = evt.StepCurrent;
        var pct = (int)((double)evt.StepCurrent / total * 100);
        _planProgressText.Text = $"{pct}%";

        // 이전 단계 완료 표시 + 현재 단계 강조
        for (int i = 0; i < _planStepsPanel.Children.Count; i++)
        {
            if (_planStepsPanel.Children[i] is StackPanel row && row.Children.Count >= 2)
            {
                var statusTb = row.Children[0] as TextBlock;
                var textTb = row.Children[1] as TextBlock;
                if (statusTb == null || textTb == null) continue;

                if (i < stepIdx)
                {
                    // 완료
                    statusTb.Text = "●";
                    statusTb.Foreground = ThemeResourceHelper.HexBrush("#16A34A");
                    textTb.Foreground = ThemeResourceHelper.HexBrush("#6B7280");
                }
                else if (i == stepIdx)
                {
                    // 현재 진행 중
                    statusTb.Text = "◉";
                    statusTb.Foreground = ThemeResourceHelper.HexBrush("#4B5EFC");
                    textTb.Foreground = ThemeResourceHelper.HexBrush("#1E293B");
                    textTb.FontWeight = FontWeights.SemiBold;
                }
                else
                {
                    // 대기
                    statusTb.Text = "○";
                    statusTb.Foreground = ThemeResourceHelper.HexBrush("#9CA3AF");
                    textTb.Foreground = ThemeResourceHelper.HexBrush("#4B5563");
                    textTb.FontWeight = FontWeights.Normal;
                }
            }
        }
    }

    /// <summary>Diff 텍스트를 색상 하이라이팅된 StackPanel로 렌더링합니다.</summary>
    private static UIElement BuildDiffView(string text)
    {
        var panel = new StackPanel
        {
            Background = ThemeResourceHelper.HexBrush("#FAFAFA"),
            MaxWidth = 520,
        };

        var diffStarted = false;
        foreach (var rawLine in text.Split('\n'))
        {
            var line = rawLine.TrimEnd('\r');

            // diff 헤더 전의 일반 텍스트
            if (!diffStarted && !line.StartsWith("--- "))
            {
                panel.Children.Add(new TextBlock
                {
                    Text = line,
                    FontSize = 11,
                    Foreground = ThemeResourceHelper.HexBrush("#4B5563"),
                    FontFamily = ThemeResourceHelper.Consolas,
                    Margin = new Thickness(0, 0, 0, 1),
                });
                continue;
            }
            diffStarted = true;

            string bgHex, fgHex;
            if (line.StartsWith("---") || line.StartsWith("+++"))
            {
                bgHex = "#F3F4F6"; fgHex = "#374151";
            }
            else if (line.StartsWith("@@"))
            {
                bgHex = "#EFF6FF"; fgHex = "#3B82F6";
            }
            else if (line.StartsWith("+"))
            {
                bgHex = "#ECFDF5"; fgHex = "#059669";
            }
            else if (line.StartsWith("-"))
            {
                bgHex = "#FEF2F2"; fgHex = "#DC2626";
            }
            else
            {
                bgHex = "Transparent"; fgHex = "#6B7280";
            }

            var tb = new TextBlock
            {
                Text = line,
                FontSize = 10.5,
                FontFamily = ThemeResourceHelper.Consolas,
                Foreground = ThemeResourceHelper.HexBrush(fgHex),
                Padding = new Thickness(4, 1, 4, 1),
            };
            if (bgHex != "Transparent")
                tb.Background = ThemeResourceHelper.HexBrush(bgHex);

            panel.Children.Add(tb);
        }

        return panel;
    }
}
