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

namespace AxCopilot.Views;

/// <summary>
/// Phase 34: 커스텀 팝업 메뉴 생성 헬퍼.
/// ChatWindow에서 6회 이상 반복되는 Popup+Border+StackPanel 패턴을 통합합니다.
///
/// 사용법:
/// <code>
/// var (popup, stack) = PopupMenuHelper.Create(targetElement, this, minWidth: 240);
/// stack.Children.Add(PopupMenuHelper.MenuItem("항목", fg, hoverBg, () => { ... popup.IsOpen = false; }));
/// popup.IsOpen = true;
/// </code>
/// </summary>
public static class PopupMenuHelper
{
    /// <summary>
    /// 테마 적용된 팝업 메뉴 (Popup + 라운드 Border + ScrollViewer + StackPanel)를 생성합니다.
    /// </summary>
    /// <param name="target">팝업의 PlacementTarget</param>
    /// <param name="owner">테마 리소스 조회용 FrameworkElement</param>
    /// <param name="placement">배치 모드 (기본: Top)</param>
    /// <param name="minWidth">최소 너비 (기본: 220)</param>
    /// <param name="maxHeight">최대 높이 (기본: 460)</param>
    /// <returns>(Popup, 내부 StackPanel) 튜플</returns>
    public static (Popup Popup, StackPanel Stack) Create(
        UIElement target,
        FrameworkElement owner,
        PlacementMode placement = PlacementMode.Top,
        double minWidth = 220,
        double maxHeight = 460)
    {
        var bg = ThemeResourceHelper.Background(owner);
        var border = ThemeResourceHelper.Border(owner);

        var popup = new Popup
        {
            StaysOpen = false,
            AllowsTransparency = true,
            PopupAnimation = PopupAnimation.Fade,
            PlacementTarget = target,
            Placement = placement,
        };

        var container = new Border
        {
            Background = bg,
            BorderBrush = border,
            BorderThickness = new Thickness(1),
            CornerRadius = new CornerRadius(12),
            Padding = new Thickness(6),
            MinWidth = minWidth,
            MaxHeight = maxHeight,
            Effect = new DropShadowEffect
            {
                BlurRadius = 16,
                ShadowDepth = 4,
                Opacity = 0.3,
                Color = Colors.Black,
            },
        };

        var scroll = new ScrollViewer
        {
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
            MaxHeight = maxHeight - 20,
        };

        var stack = new StackPanel();
        scroll.Content = stack;
        container.Child = scroll;
        popup.Child = container;

        return (popup, stack);
    }

    /// <summary>
    /// 팝업 메뉴 항목 (Border + Grid: 텍스트 + 체크 아이콘)을 생성합니다.
    /// </summary>
    public static Border MenuItem(
        string text,
        Brush foreground,
        Brush hoverBackground,
        Action? onClick = null,
        bool isChecked = false,
        string? icon = null,
        Brush? iconColor = null,
        double fontSize = 13)
    {
        var item = new Border
        {
            Background = Brushes.Transparent,
            CornerRadius = new CornerRadius(8),
            Padding = new Thickness(10, 7, 10, 7),
            Margin = new Thickness(0, 1, 0, 1),
            Cursor = Cursors.Hand,
        };

        var grid = new Grid();
        // 아이콘 열 (옵션)
        if (!string.IsNullOrEmpty(icon))
        {
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(24) });
            var iconTb = new TextBlock
            {
                Text = icon,
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 13,
                Foreground = iconColor ?? foreground,
                VerticalAlignment = VerticalAlignment.Center,
            };
            Grid.SetColumn(iconTb, 0);
            grid.Children.Add(iconTb);
        }

        // 텍스트 열
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        var textTb = new TextBlock
        {
            Text = text,
            FontSize = fontSize,
            Foreground = foreground,
            VerticalAlignment = VerticalAlignment.Center,
        };
        Grid.SetColumn(textTb, string.IsNullOrEmpty(icon) ? 0 : 1);
        grid.Children.Add(textTb);

        // 체크 아이콘 열
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(20) });
        if (isChecked)
        {
            var check = new TextBlock
            {
                Text = "\uE73E",
                FontFamily = ThemeResourceHelper.SegoeMdl2,
                FontSize = 12,
                Foreground = ThemeResourceHelper.Brush("AccentColor", Brushes.DodgerBlue),
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Right,
            };
            Grid.SetColumn(check, string.IsNullOrEmpty(icon) ? 1 : 2);
            grid.Children.Add(check);
        }

        item.Child = grid;

        // 호버 효과
        item.MouseEnter += (_, _) => item.Background = hoverBackground;
        item.MouseLeave += (_, _) => item.Background = Brushes.Transparent;

        if (onClick != null)
            item.MouseLeftButtonUp += (_, _) => onClick();

        return item;
    }

    /// <summary>구분선을 생성합니다.</summary>
    public static Border Separator(Brush? color = null)
    {
        return new Border
        {
            Height = 1,
            Background = color ?? ThemeResourceHelper.Brush("SeparatorColor", Brushes.Gray),
            Margin = new Thickness(8, 4, 8, 4),
        };
    }

    /// <summary>섹션 제목을 생성합니다.</summary>
    public static TextBlock SectionHeader(string text, Brush? foreground = null)
    {
        return new TextBlock
        {
            Text = text,
            FontSize = 11,
            FontWeight = FontWeights.SemiBold,
            Foreground = foreground ?? ThemeResourceHelper.Brush("SecondaryText", Brushes.Gray),
            Margin = new Thickness(10, 8, 10, 4),
        };
    }
}
