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

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 계획 뷰어 ────────────────────────────────────────────────────────

    private Border? _planningCard;
    private StackPanel? _planStepsPanel;
    private ProgressBar? _planProgressBar;
    private TextBlock? _planProgressText;

    /// <summary>작업 계획 카드를 생성합니다 (단계 목록 + 진행률 바).</summary>
    private void AddPlanningCard(AgentEvent evt)
    {
        var steps = evt.Steps!;

        var card = new Border
        {
            Background = ThemeResourceHelper.HexBrush("#F0F4FF"),
            CornerRadius = new CornerRadius(10),
            Padding = new Thickness(14, 10, 14, 10),
            Margin = new Thickness(40, 4, 80, 4),
            HorizontalAlignment = HorizontalAlignment.Left,
            MaxWidth = 560,
        };

        var sp = new StackPanel();

        // 헤더
        var header = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 6) };
        header.Children.Add(new TextBlock
        {
            Text = "\uE9D5", // plan icon
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 13,
            Foreground = ThemeResourceHelper.HexBrush("#4B5EFC"),
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 6, 0),
        });
        header.Children.Add(new TextBlock
        {
            Text = $"작업 계획 — {steps.Count}단계",
            FontSize = 12.5, FontWeight = FontWeights.SemiBold,
            Foreground = ThemeResourceHelper.HexBrush("#3730A3"),
            VerticalAlignment = VerticalAlignment.Center,
        });
        sp.Children.Add(header);

        // 진행률 바
        var progressGrid = new Grid { Margin = new Thickness(0, 0, 0, 8) };
        progressGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        progressGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

        _planProgressBar = new ProgressBar
        {
            Minimum = 0,
            Maximum = steps.Count,
            Value = 0,
            Height = 4,
            Foreground = ThemeResourceHelper.HexBrush("#4B5EFC"),
            Background = ThemeResourceHelper.HexBrush("#D0D5FF"),
            VerticalAlignment = VerticalAlignment.Center,
        };
        // Remove the default border on ProgressBar
        _planProgressBar.BorderThickness = new Thickness(0);
        Grid.SetColumn(_planProgressBar, 0);
        progressGrid.Children.Add(_planProgressBar);

        _planProgressText = new TextBlock
        {
            Text = "0%",
            FontSize = 10.5, FontWeight = FontWeights.SemiBold,
            Foreground = ThemeResourceHelper.HexBrush("#4B5EFC"),
            Margin = new Thickness(8, 0, 0, 0),
            VerticalAlignment = VerticalAlignment.Center,
        };
        Grid.SetColumn(_planProgressText, 1);
        progressGrid.Children.Add(_planProgressText);
        sp.Children.Add(progressGrid);

        // 단계 목록
        _planStepsPanel = new StackPanel();
        for (int i = 0; i < steps.Count; i++)
        {
            var stepRow = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(0, 1, 0, 1),
                Tag = i, // 인덱스 저장
            };

            stepRow.Children.Add(new TextBlock
            {
                Text = "○", // 빈 원 (미완료)
                FontSize = 11,
                Foreground = ThemeResourceHelper.HexBrush("#9CA3AF"),
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 6, 0),
                Tag = "status",
            });
            stepRow.Children.Add(new TextBlock
            {
                Text = $"{i + 1}. {steps[i]}",
                FontSize = 11.5,
                Foreground = ThemeResourceHelper.HexBrush("#4B5563"),
                TextWrapping = TextWrapping.Wrap,
                MaxWidth = 480,
                VerticalAlignment = VerticalAlignment.Center,
            });

            _planStepsPanel.Children.Add(stepRow);
        }
        sp.Children.Add(_planStepsPanel);

        card.Child = sp;
        _planningCard = card;

        // 페이드인
        card.Opacity = 0;
        card.BeginAnimation(UIElement.OpacityProperty,
            new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(300)));

        MessagePanel.Children.Add(card);
    }

    /// <summary>계획 카드 아래에 승인/수정/취소 의사결정 버튼을 추가합니다.</summary>
    private void AddDecisionButtons(TaskCompletionSource<string?> tcs, List<string> options)
    {
        var accentBrush = ThemeResourceHelper.Accent(this);
        var accentColor = ((SolidColorBrush)accentBrush).Color;
        var secondaryText = ThemeResourceHelper.Secondary(this);

        var container = new Border
        {
            Margin = new Thickness(40, 2, 80, 6),
            HorizontalAlignment = HorizontalAlignment.Left,
            MaxWidth = 560,
        };

        var outerStack = new StackPanel();

        // 버튼 행
        var btnRow = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 0) };

        // 승인 버튼 (강조)
        var approveBtn = new Border
        {
            Background = accentBrush,
            CornerRadius = new CornerRadius(16),
            Padding = new Thickness(16, 7, 16, 7),
            Margin = new Thickness(0, 0, 8, 0),
            Cursor = Cursors.Hand,
        };
        var approveSp = new StackPanel { Orientation = Orientation.Horizontal };
        approveSp.Children.Add(new TextBlock
        {
            Text = "\uE73E", FontFamily = ThemeResourceHelper.SegoeMdl2, FontSize = 11,
            Foreground = Brushes.White, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 5, 0),
        });
        approveSp.Children.Add(new TextBlock { Text = "승인", FontSize = 12.5, FontWeight = FontWeights.SemiBold, Foreground = Brushes.White });
        approveBtn.Child = approveSp;
        ApplyMenuItemHover(approveBtn);
        approveBtn.MouseLeftButtonUp += (_, _) =>
        {
            CollapseDecisionButtons(outerStack, "✓ 승인됨", accentBrush);
            tcs.TrySetResult(null); // null = 승인
        };
        btnRow.Children.Add(approveBtn);

        // 수정 요청 버튼
        var editBtn = new Border
        {
            Background = new SolidColorBrush(Color.FromArgb(0x18, accentColor.R, accentColor.G, accentColor.B)),
            CornerRadius = new CornerRadius(16),
            Padding = new Thickness(14, 7, 14, 7),
            Margin = new Thickness(0, 0, 8, 0),
            Cursor = Cursors.Hand,
            BorderBrush = new SolidColorBrush(Color.FromArgb(0x40, accentColor.R, accentColor.G, accentColor.B)),
            BorderThickness = new Thickness(1),
        };
        var editSp = new StackPanel { Orientation = Orientation.Horizontal };
        editSp.Children.Add(new TextBlock
        {
            Text = "\uE70F", FontFamily = ThemeResourceHelper.SegoeMdl2, FontSize = 11,
            Foreground = accentBrush, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 5, 0),
        });
        editSp.Children.Add(new TextBlock { Text = "수정 요청", FontSize = 12.5, FontWeight = FontWeights.SemiBold, Foreground = accentBrush });
        editBtn.Child = editSp;
        ApplyMenuItemHover(editBtn);

        // 수정 요청용 텍스트 입력 패널 (초기 숨김)
        var editInputPanel = new Border
        {
            Visibility = Visibility.Collapsed,
            Background = ThemeResourceHelper.HexBrush("#F8F9FC"),
            CornerRadius = new CornerRadius(10),
            Padding = new Thickness(10, 8, 10, 8),
            Margin = new Thickness(0, 8, 0, 0),
        };
        var editInputStack = new StackPanel();
        editInputStack.Children.Add(new TextBlock
        {
            Text = "수정 사항을 입력하세요:",
            FontSize = 11.5, Foreground = secondaryText,
            Margin = new Thickness(0, 0, 0, 6),
        });
        var editTextBox = new TextBox
        {
            MinHeight = 36,
            MaxHeight = 100,
            AcceptsReturn = true,
            TextWrapping = TextWrapping.Wrap,
            FontSize = 12.5,
            Background = Brushes.White,
            BorderBrush = new SolidColorBrush(Color.FromArgb(0x40, accentColor.R, accentColor.G, accentColor.B)),
            BorderThickness = new Thickness(1),
            Padding = new Thickness(8, 6, 8, 6),
        };
        editInputStack.Children.Add(editTextBox);

        var submitEditBtn = new Border
        {
            Background = accentBrush,
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(12, 5, 12, 5),
            Margin = new Thickness(0, 6, 0, 0),
            Cursor = Cursors.Hand,
            HorizontalAlignment = HorizontalAlignment.Right,
        };
        submitEditBtn.Child = new TextBlock { Text = "전송", FontSize = 12, FontWeight = FontWeights.SemiBold, Foreground = Brushes.White };
        ApplyHoverScaleAnimation(submitEditBtn, 1.05);
        submitEditBtn.MouseLeftButtonUp += (_, _) =>
        {
            var feedback = editTextBox.Text.Trim();
            if (string.IsNullOrEmpty(feedback)) return;
            CollapseDecisionButtons(outerStack, "✎ 수정 요청됨", accentBrush);
            tcs.TrySetResult(feedback);
        };
        editInputStack.Children.Add(submitEditBtn);
        editInputPanel.Child = editInputStack;

        editBtn.MouseLeftButtonUp += (_, _) =>
        {
            editInputPanel.Visibility = editInputPanel.Visibility == Visibility.Visible
                ? Visibility.Collapsed : Visibility.Visible;
            if (editInputPanel.Visibility == Visibility.Visible)
                editTextBox.Focus();
        };
        btnRow.Children.Add(editBtn);

        // 취소 버튼
        var cancelBtn = new Border
        {
            Background = Brushes.Transparent,
            CornerRadius = new CornerRadius(16),
            Padding = new Thickness(14, 7, 14, 7),
            Cursor = Cursors.Hand,
            BorderBrush = new SolidColorBrush(Color.FromArgb(0x30, 0xDC, 0x26, 0x26)),
            BorderThickness = new Thickness(1),
        };
        var cancelSp = new StackPanel { Orientation = Orientation.Horizontal };
        cancelSp.Children.Add(new TextBlock
        {
            Text = "\uE711", FontFamily = ThemeResourceHelper.SegoeMdl2, FontSize = 11,
            Foreground = new SolidColorBrush(Color.FromRgb(0xDC, 0x26, 0x26)),
            VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 5, 0),
        });
        cancelSp.Children.Add(new TextBlock
        {
            Text = "취소", FontSize = 12.5, FontWeight = FontWeights.SemiBold,
            Foreground = new SolidColorBrush(Color.FromRgb(0xDC, 0x26, 0x26)),
        });
        cancelBtn.Child = cancelSp;
        ApplyMenuItemHover(cancelBtn);
        cancelBtn.MouseLeftButtonUp += (_, _) =>
        {
            CollapseDecisionButtons(outerStack, "✕ 취소됨",
                new SolidColorBrush(Color.FromRgb(0xDC, 0x26, 0x26)));
            tcs.TrySetResult("취소");
        };
        btnRow.Children.Add(cancelBtn);

        outerStack.Children.Add(btnRow);
        outerStack.Children.Add(editInputPanel);
        container.Child = outerStack;

        // 슬라이드 + 페이드 등장 애니메이션
        ApplyMessageEntryAnimation(container);
        MessagePanel.Children.Add(container);
        ForceScrollToEnd(); // 의사결정 버튼 표시 시 강제 하단 이동

        // PlanViewerWindow 등 외부에서 TCS가 완료되면 인라인 버튼도 자동 접기
        var capturedOuterStack = outerStack;
        var capturedAccent = accentBrush;
        _ = tcs.Task.ContinueWith(t =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                // 이미 접혀있으면 스킵 (인라인 버튼으로 직접 클릭한 경우)
                if (capturedOuterStack.Children.Count <= 1) return;

                var label = t.Result == null ? "✓ 승인됨"
                    : t.Result == "취소" ? "✕ 취소됨"
                    : "✎ 수정 요청됨";
                var fg = t.Result == "취소"
                    ? new SolidColorBrush(Color.FromRgb(0xDC, 0x26, 0x26))
                    : capturedAccent;
                CollapseDecisionButtons(capturedOuterStack, label, fg);
            });
        }, TaskScheduler.Default);
    }

    /// <summary>의사결정 버튼을 숨기고 결과 라벨로 교체합니다.</summary>
    private void CollapseDecisionButtons(StackPanel outerStack, string resultText, Brush fg)
    {
        outerStack.Children.Clear();
        var resultLabel = new TextBlock
        {
            Text = resultText,
            FontSize = 12,
            FontWeight = FontWeights.SemiBold,
            Foreground = fg,
            Opacity = 0.8,
            Margin = new Thickness(0, 2, 0, 2),
        };
        outerStack.Children.Add(resultLabel);
    }

    // ════════════════════════════════════════════════════════════
    //  실행 계획 뷰어 (PlanViewerWindow) 연동
    // ════════════════════════════════════════════════════════════

    /// <summary>PlanViewerWindow를 사용하는 UserDecisionCallback을 생성합니다.</summary>
    private Func<string, List<string>, Task<string?>> CreatePlanDecisionCallback()
    {
        return async (planSummary, options) =>
        {
            var tcs = new TaskCompletionSource<string?>();
            var steps = Services.Agent.TaskDecomposer.ExtractSteps(planSummary);

            await Dispatcher.InvokeAsync(() =>
            {
                // PlanViewerWindow 생성 또는 재사용
                if (_planViewerWindow == null || !IsWindowAlive(_planViewerWindow))
                {
                    _planViewerWindow = new PlanViewerWindow();
                    _planViewerWindow.Closing += (_, e) =>
                    {
                        e.Cancel = true;
                        _planViewerWindow.Hide();
                    };
                }

                // 계획 표시 + 승인 대기
                _planViewerWindow.ShowPlanAsync(planSummary, steps, tcs);

                // 채팅 창에 간략 배너 추가 + 인라인 승인 버튼도 표시
                AddDecisionButtons(tcs, options);

                // 하단 바 계획 버튼 표시
                ShowPlanButton(true);
            });

            // 5분 타임아웃
            var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromMinutes(5)));
            if (completed != tcs.Task)
            {
                await Dispatcher.InvokeAsync(() => _planViewerWindow?.Hide());
                return "취소";
            }

            var result = await tcs.Task;

            // 승인된 경우 — 실행 모드로 전환
            if (result == null) // null = 승인
            {
                await Dispatcher.InvokeAsync(() =>
                {
                    _planViewerWindow?.SwitchToExecutionMode();
                    _planViewerWindow?.Hide(); // 숨기고 하단 버튼으로 다시 열기
                });
            }
            else
            {
                await Dispatcher.InvokeAsync(() => _planViewerWindow?.Hide());
            }

            return result;
        };
    }

    /// <summary>하단 바에 계획 보기 버튼을 표시/숨김합니다.</summary>
    private void ShowPlanButton(bool show)
    {
        if (!show)
        {
            // 계획 버튼 제거
            for (int i = MoodIconPanel.Children.Count - 1; i >= 0; i--)
            {
                if (MoodIconPanel.Children[i] is Border b && b.Tag?.ToString() == "PlanBtn")
                {
                    // 앞의 구분선도 제거
                    if (i > 0 && MoodIconPanel.Children[i - 1] is Border sep && sep.Tag?.ToString() == "PlanSep")
                        MoodIconPanel.Children.RemoveAt(i - 1);
                    if (i < MoodIconPanel.Children.Count)
                        MoodIconPanel.Children.RemoveAt(Math.Min(i, MoodIconPanel.Children.Count - 1));
                    break;
                }
            }
            return;
        }

        // 이미 있으면 무시
        foreach (var child in MoodIconPanel.Children)
        {
            if (child is Border b && b.Tag?.ToString() == "PlanBtn") return;
        }

        // 구분선
        var separator = new Border
        {
            Width = 1, Height = 18,
            Background = ThemeResourceHelper.Separator(this),
            Margin = new Thickness(4, 0, 4, 0),
            VerticalAlignment = VerticalAlignment.Center,
            Tag = "PlanSep",
        };
        MoodIconPanel.Children.Add(separator);

        // 계획 버튼
        var planBtn = CreateFolderBarButton("\uE9D2", "계획", "실행 계획 보기", "#10B981");
        planBtn.Tag = "PlanBtn";
        planBtn.MouseLeftButtonUp += (_, e) =>
        {
            e.Handled = true;
            if (_planViewerWindow != null && IsWindowAlive(_planViewerWindow))
            {
                _planViewerWindow.Show();
                _planViewerWindow.Activate();
            }
        };
        MoodIconPanel.Children.Add(planBtn);
    }

    /// <summary>계획 뷰어에서 현재 실행 단계를 갱신합니다.</summary>
    private void UpdatePlanViewerStep(AgentEvent evt)
    {
        if (_planViewerWindow == null || !IsWindowAlive(_planViewerWindow)) return;
        if (evt.StepCurrent > 0)
            _planViewerWindow.UpdateCurrentStep(evt.StepCurrent - 1); // 0-based
    }

    /// <summary>계획 실행 완료를 뷰어에 알립니다.</summary>
    private void CompletePlanViewer()
    {
        if (_planViewerWindow != null && IsWindowAlive(_planViewerWindow))
            _planViewerWindow.MarkComplete();
        ShowPlanButton(false);
    }

    private static bool IsWindowAlive(Window? w)
    {
        if (w == null) return false;
        try { var _ = w.IsVisible; return true; }
        catch (Exception) { return false; }
    }
}
