using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace AxCopilot.Views;

internal sealed partial class PlanViewerWindow
{
    // ════════════════════════════════════════════════════════════
    // 버튼 빌더 + 유틸리티
    // ════════════════════════════════════════════════════════════

    private void BuildApprovalButtons()
    {
        _btnPanel.Children.Clear();
        var accentBrush = Application.Current.TryFindResource("AccentColor") as Brush
                          ?? new SolidColorBrush(Color.FromRgb(0x4B, 0x5E, 0xFC));

        var approveBtn = CreateActionButton("\uE73E", "승인", accentBrush, Brushes.White, true);
        approveBtn.MouseLeftButtonUp += (_, _) =>
        {
            _tcs?.TrySetResult(null);
            SwitchToExecutionMode();
        };
        _btnPanel.Children.Add(approveBtn);

        var editBtn = CreateActionButton("\uE70F", "수정 요청", accentBrush, accentBrush, false);
        editBtn.MouseLeftButtonUp += (_, _) => ShowEditInput();
        _btnPanel.Children.Add(editBtn);

        var reconfirmBtn = CreateActionButton("\uE72C", "재확인",
            Application.Current.TryFindResource("SecondaryText") as Brush ?? Brushes.Gray,
            Application.Current.TryFindResource("PrimaryText") as Brush ?? Brushes.White, false);
        reconfirmBtn.MouseLeftButtonUp += (_, _) =>
            _tcs?.TrySetResult("계획을 다시 검토하고 더 구체적으로 수정해주세요.");
        _btnPanel.Children.Add(reconfirmBtn);

        var cancelBrush = new SolidColorBrush(Color.FromRgb(0xDC, 0x26, 0x26));
        var cancelBtn = CreateActionButton("\uE711", "취소", cancelBrush, cancelBrush, false);
        cancelBtn.MouseLeftButtonUp += (_, _) => { _tcs?.TrySetResult("취소"); Hide(); };
        _btnPanel.Children.Add(cancelBtn);
    }

    private void BuildExecutionButtons()
    {
        _btnPanel.Children.Clear();
        var secondaryText = Application.Current.TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var hideBtn = CreateActionButton("\uE921", "숨기기", secondaryText,
            Application.Current.TryFindResource("PrimaryText") as Brush ?? Brushes.White, false);
        hideBtn.MouseLeftButtonUp += (_, _) => Hide();
        _btnPanel.Children.Add(hideBtn);
    }

    private void BuildCloseButton()
    {
        _btnPanel.Children.Clear();
        var accentBrush = Application.Current.TryFindResource("AccentColor") as Brush
                          ?? new SolidColorBrush(Color.FromRgb(0x4B, 0x5E, 0xFC));
        var closeBtn = CreateActionButton("\uE73E", "닫기", accentBrush, Brushes.White, true);
        closeBtn.MouseLeftButtonUp += (_, _) => Hide();
        _btnPanel.Children.Add(closeBtn);
    }

    private void ShowEditInput()
    {
        var editPanel = new Border
        {
            Margin          = new Thickness(20, 0, 20, 12),
            Padding         = new Thickness(12, 8, 12, 8),
            CornerRadius    = new CornerRadius(10),
            Background      = Application.Current.TryFindResource("ItemBackground") as Brush
                              ?? new SolidColorBrush(Color.FromRgb(0x2A, 0x2B, 0x40)),
        };
        var editStack = new StackPanel();
        editStack.Children.Add(new TextBlock
        {
            Text = "수정 사항을 입력하세요:",
            FontSize = 11.5,
            Foreground = Application.Current.TryFindResource("SecondaryText") as Brush ?? Brushes.Gray,
            Margin = new Thickness(0, 0, 0, 6),
        });
        var textBox = new TextBox
        {
            MinHeight       = 44,
            MaxHeight       = 120,
            AcceptsReturn   = true,
            TextWrapping    = TextWrapping.Wrap,
            FontSize        = 13,
            Background      = Application.Current.TryFindResource("LauncherBackground") as Brush
                              ?? new SolidColorBrush(Color.FromRgb(0x1A, 0x1B, 0x2E)),
            Foreground      = Application.Current.TryFindResource("PrimaryText") as Brush ?? Brushes.White,
            CaretBrush      = Application.Current.TryFindResource("PrimaryText") as Brush ?? Brushes.White,
            BorderBrush     = Application.Current.TryFindResource("BorderColor") as Brush ?? Brushes.Gray,
            BorderThickness = new Thickness(1),
            Padding         = new Thickness(10, 8, 10, 8),
        };
        editStack.Children.Add(textBox);

        var accentBrush = Application.Current.TryFindResource("AccentColor") as Brush
                          ?? new SolidColorBrush(Color.FromRgb(0x4B, 0x5E, 0xFC));
        var sendBtn = new Border
        {
            Background  = accentBrush,
            CornerRadius = new CornerRadius(8),
            Padding     = new Thickness(14, 6, 14, 6),
            Margin      = new Thickness(0, 8, 0, 0),
            Cursor      = Cursors.Hand,
            HorizontalAlignment = HorizontalAlignment.Right,
            Child = new TextBlock
            {
                Text = "전송", FontSize = 12.5, FontWeight = FontWeights.SemiBold, Foreground = Brushes.White,
            },
        };
        sendBtn.MouseEnter += (s, _) => ((Border)s).Opacity = 0.85;
        sendBtn.MouseLeave += (s, _) => ((Border)s).Opacity = 1.0;
        sendBtn.MouseLeftButtonUp += (_, _) =>
        {
            var feedback = textBox.Text.Trim();
            if (string.IsNullOrEmpty(feedback)) return;
            _tcs?.TrySetResult(feedback);
        };
        editStack.Children.Add(sendBtn);
        editPanel.Child = editStack;

        if (_btnPanel.Parent is Grid parentGrid)
        {
            for (int i = parentGrid.Children.Count - 1; i >= 0; i--)
            {
                if (parentGrid.Children[i] is Border b && b.Tag?.ToString() == "EditPanel")
                    parentGrid.Children.RemoveAt(i);
            }
            editPanel.Tag = "EditPanel";
            Grid.SetRow(editPanel, 4); // row 4 = 하단 버튼 행 (toolBar 추가로 1 증가)
            parentGrid.Children.Add(editPanel);
            _btnPanel.Margin = new Thickness(20, 0, 20, 16);
            textBox.Focus();
        }
    }

    // ════════════════════════════════════════════════════════════
    // 공통 버튼 팩토리
    // ════════════════════════════════════════════════════════════

    private static Border CreateMiniButton(string icon, Brush fg, Brush hoverBg)
    {
        var btn = new Border
        {
            Width = 24, Height = 24,
            CornerRadius = new CornerRadius(6),
            Background = Brushes.Transparent,
            Cursor = Cursors.Hand,
            Margin = new Thickness(1, 0, 1, 0),
            Child = new TextBlock
            {
                Text = icon, FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 10, Foreground = fg,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Center,
            },
        };
        btn.MouseEnter += (s, _) => ((Border)s).Background = hoverBg;
        btn.MouseLeave += (s, _) => ((Border)s).Background = Brushes.Transparent;
        return btn;
    }

    private static Border CreateActionButton(string icon, string text, Brush borderColor,
        Brush textColor, bool filled)
    {
        var color = ((SolidColorBrush)borderColor).Color;
        var btn = new Border
        {
            CornerRadius    = new CornerRadius(12),
            Padding         = new Thickness(16, 8, 16, 8),
            Margin          = new Thickness(4, 0, 4, 0),
            Cursor          = Cursors.Hand,
            Background      = filled ? borderColor
                : new SolidColorBrush(Color.FromArgb(0x18, color.R, color.G, color.B)),
            BorderBrush     = filled ? Brushes.Transparent
                : new SolidColorBrush(Color.FromArgb(0x80, color.R, color.G, color.B)),
            BorderThickness = new Thickness(filled ? 0 : 1.2),
        };
        var sp = new StackPanel { Orientation = Orientation.Horizontal };
        sp.Children.Add(new TextBlock
        {
            Text = icon, FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 12, Foreground = filled ? Brushes.White : textColor,
            VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 6, 0),
        });
        sp.Children.Add(new TextBlock
        {
            Text = text, FontSize = 12.5, FontWeight = FontWeights.SemiBold,
            Foreground = filled ? Brushes.White : textColor,
        });
        btn.Child = sp;
        btn.MouseEnter += (s, _) => ((Border)s).Opacity = 0.85;
        btn.MouseLeave += (s, _) => ((Border)s).Opacity = 1.0;
        return btn;
    }
}
