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

namespace AxCopilot.Views;

/// <summary>프롬프트 템플릿 추가/편집 다이얼로그.</summary>
internal sealed class PromptTemplateDialog : Window
{
    private readonly TextBox _nameBox;
    private readonly TextBox _contentBox;

    public string TemplateName => _nameBox.Text.Trim();
    public string TemplateContent => _contentBox.Text.Trim();

    public PromptTemplateDialog(string existingName = "", string existingContent = "")
    {
        bool isEdit = !string.IsNullOrEmpty(existingName);
        Title = isEdit ? "템플릿 편집" : "템플릿 추가";
        Width = 480;
        SizeToContent = SizeToContent.Height;
        WindowStartupLocation = WindowStartupLocation.CenterOwner;
        ResizeMode = ResizeMode.NoResize;
        WindowStyle = WindowStyle.None;
        AllowsTransparency = true;
        Background = Brushes.Transparent;

        var bgBrush = Application.Current.TryFindResource("LauncherBackground") as Brush
                      ?? new SolidColorBrush(Color.FromRgb(0x1A, 0x1B, 0x2E));
        var primaryText = Application.Current.TryFindResource("PrimaryText") as Brush ?? Brushes.White;
        var secondaryText = Application.Current.TryFindResource("SecondaryText") as Brush ?? Brushes.Gray;
        var accentBrush = Application.Current.TryFindResource("AccentColor") as Brush ?? Brushes.Blue;
        var itemBg = Application.Current.TryFindResource("ItemBackground") as Brush
                     ?? new SolidColorBrush(Color.FromRgb(0x2A, 0x2B, 0x40));
        var borderBrush = Application.Current.TryFindResource("BorderColor") as Brush ?? Brushes.Gray;

        // 루트 컨테이너
        var root = new Border
        {
            Background = bgBrush,
            CornerRadius = new CornerRadius(16),
            BorderBrush = borderBrush,
            BorderThickness = new Thickness(1),
            Padding = new Thickness(28, 24, 28, 24),
            Effect = new System.Windows.Media.Effects.DropShadowEffect
            {
                BlurRadius = 24,
                ShadowDepth = 4,
                Opacity = 0.3,
                Color = Colors.Black,
            },
        };

        var stack = new StackPanel();

        // 헤더
        var header = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 20) };
        header.Children.Add(new TextBlock
        {
            Text = "\uE8A5",
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 18,
            Foreground = accentBrush,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 10, 0),
        });
        header.Children.Add(new TextBlock
        {
            Text = isEdit ? "템플릿 편집" : "새 프롬프트 템플릿",
            FontSize = 17,
            FontWeight = FontWeights.Bold,
            Foreground = primaryText,
            VerticalAlignment = VerticalAlignment.Center,
        });
        stack.Children.Add(header);

        // 템플릿 이름 입력
        stack.Children.Add(new TextBlock
        {
            Text = "템플릿 이름",
            FontSize = 12,
            FontWeight = FontWeights.SemiBold,
            Foreground = primaryText,
            Margin = new Thickness(0, 0, 0, 6),
        });
        stack.Children.Add(new TextBlock
        {
            Text = "목록에 표시될 이름입니다. 예: 코드 리뷰 요청, 번역 요청",
            FontSize = 11,
            Foreground = secondaryText,
            Margin = new Thickness(0, 0, 0, 8),
        });
        _nameBox = new TextBox
        {
            Text = existingName,
            FontSize = 13,
            Padding = new Thickness(12, 8, 12, 8),
            Foreground = primaryText,
            Background = itemBg,
            CaretBrush = accentBrush,
            BorderBrush = borderBrush,
            BorderThickness = new Thickness(1),
        };
        var nameBorder = new Border { CornerRadius = new CornerRadius(8), ClipToBounds = true, Child = _nameBox };
        stack.Children.Add(nameBorder);

        // 구분선
        stack.Children.Add(new Rectangle
        {
            Height = 1,
            Fill = borderBrush,
            Margin = new Thickness(0, 16, 0, 16),
            Opacity = 0.5,
        });

        // 프롬프트 내용 입력
        stack.Children.Add(new TextBlock
        {
            Text = "프롬프트 내용",
            FontSize = 12,
            FontWeight = FontWeights.SemiBold,
            Foreground = primaryText,
            Margin = new Thickness(0, 0, 0, 6),
        });
        stack.Children.Add(new TextBlock
        {
            Text = "채팅 입력란에 자동으로 삽입될 텍스트입니다.",
            FontSize = 11,
            Foreground = secondaryText,
            Margin = new Thickness(0, 0, 0, 8),
        });
        _contentBox = new TextBox
        {
            Text = existingContent,
            FontSize = 13,
            Padding = new Thickness(12, 8, 12, 8),
            Foreground = primaryText,
            Background = itemBg,
            CaretBrush = accentBrush,
            BorderBrush = borderBrush,
            BorderThickness = new Thickness(1),
            AcceptsReturn = true,
            TextWrapping = TextWrapping.Wrap,
            MinHeight = 100,
            MaxHeight = 240,
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
        };
        var contentBorder = new Border { CornerRadius = new CornerRadius(8), ClipToBounds = true, Child = _contentBox };
        stack.Children.Add(contentBorder);

        // 글자 수 표시
        var charCount = new TextBlock
        {
            FontSize = 10.5,
            Foreground = secondaryText,
            Margin = new Thickness(0, 6, 0, 0),
            HorizontalAlignment = HorizontalAlignment.Right,
        };
        UpdateCharCount(charCount);
        _contentBox.TextChanged += (_, _) => UpdateCharCount(charCount);
        stack.Children.Add(charCount);

        // 버튼 바
        var btnBar = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            HorizontalAlignment = HorizontalAlignment.Right,
            Margin = new Thickness(0, 20, 0, 0),
        };

        var cancelBtn = new Button
        {
            Content = "취소",
            Width = 80,
            Padding = new Thickness(0, 8, 0, 8),
            Margin = new Thickness(0, 0, 10, 0),
            Background = Brushes.Transparent,
            Foreground = secondaryText,
            BorderBrush = borderBrush,
            BorderThickness = new Thickness(1),
            Cursor = Cursors.Hand,
            FontSize = 13,
        };
        cancelBtn.Click += (_, _) => { DialogResult = false; Close(); };
        btnBar.Children.Add(cancelBtn);

        var okBtn = new Button
        {
            Content = isEdit ? "저장" : "추가",
            Width = 80,
            Padding = new Thickness(0, 8, 0, 8),
            Background = accentBrush,
            Foreground = Brushes.White,
            BorderThickness = new Thickness(0),
            Cursor = Cursors.Hand,
            FontSize = 13,
            FontWeight = FontWeights.SemiBold,
        };
        okBtn.Click += (_, _) =>
        {
            if (string.IsNullOrWhiteSpace(_nameBox.Text))
            {
                CustomMessageBox.Show("템플릿 이름을 입력하세요.", "입력 오류", MessageBoxButton.OK, MessageBoxImage.Warning);
                _nameBox.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(_contentBox.Text))
            {
                CustomMessageBox.Show("프롬프트 내용을 입력하세요.", "입력 오류", MessageBoxButton.OK, MessageBoxImage.Warning);
                _contentBox.Focus();
                return;
            }
            DialogResult = true;
            Close();
        };
        btnBar.Children.Add(okBtn);
        stack.Children.Add(btnBar);

        root.Child = stack;
        Content = root;

        // 키보드 핸들링
        KeyDown += (_, ke) =>
        {
            if (ke.Key == Key.Escape) { DialogResult = false; Close(); }
        };
        Loaded += (_, _) => { _nameBox.Focus(); _nameBox.SelectAll(); };

        // 드래그 이동
        root.MouseLeftButtonDown += (_, me) =>
        {
            if (me.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
                try { DragMove(); } catch (Exception) { }
        };
    }

    private void UpdateCharCount(TextBlock tb)
    {
        var len = _contentBox.Text.Length;
        tb.Text = $"{len}자";
    }
}
