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

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 액션·피드백 버튼 ───────────────────────────────────────────────

    private Button CreateActionButton(string symbol, string tooltip, Brush foreground, Action onClick)
    {
        var hoverBrush = ThemeResourceHelper.Primary(this);
        var icon = new TextBlock
        {
            Text = symbol,
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 12,
            Foreground = foreground,
            VerticalAlignment = VerticalAlignment.Center
        };
        var btn = new Button
        {
            Content = icon,
            Background = Brushes.Transparent,
            BorderThickness = new Thickness(0),
            Cursor = Cursors.Hand,
            Padding = new Thickness(6, 4, 6, 4),
            Margin = new Thickness(0, 0, 4, 0),
            ToolTip = tooltip
        };
        btn.MouseEnter += (_, _) => icon.Foreground = hoverBrush;
        btn.MouseLeave += (_, _) => icon.Foreground = foreground;
        btn.Click += (_, _) => onClick();
        ApplyHoverScaleAnimation(btn, 1.15);
        return btn;
    }

    /// <summary>좋아요/싫어요 토글 피드백 버튼 (상태 영구 저장)</summary>
    private Button CreateFeedbackButton(string outline, string filled, string tooltip,
        Brush normalColor, Brush activeColor, ChatMessage? message = null, string feedbackType = "",
        Action? resetSibling = null, Action<Action>? registerReset = null)
    {
        var hoverBrush = ThemeResourceHelper.Primary(this);
        var isActive = message?.Feedback == feedbackType;
        var icon = new TextBlock
        {
            Text = isActive ? filled : outline,
            FontFamily = ThemeResourceHelper.SegoeMdl2,
            FontSize = 12,
            Foreground = isActive ? activeColor : normalColor,
            VerticalAlignment = VerticalAlignment.Center,
            RenderTransformOrigin = new Point(0.5, 0.5),
            RenderTransform = new ScaleTransform(1, 1)
        };
        var btn = new Button
        {
            Content = icon,
            Background = Brushes.Transparent,
            BorderThickness = new Thickness(0),
            Cursor = Cursors.Hand,
            Padding = new Thickness(6, 4, 6, 4),
            Margin = new Thickness(0, 0, 4, 0),
            ToolTip = tooltip
        };
        // 상대 버튼이 리셋할 수 있도록 등록
        registerReset?.Invoke(() =>
        {
            isActive = false;
            icon.Text = outline;
            icon.Foreground = normalColor;
        });
        btn.MouseEnter += (_, _) => { if (!isActive) icon.Foreground = hoverBrush; };
        btn.MouseLeave += (_, _) => { if (!isActive) icon.Foreground = normalColor; };
        btn.Click += (_, _) =>
        {
            isActive = !isActive;
            icon.Text = isActive ? filled : outline;
            icon.Foreground = isActive ? activeColor : normalColor;

            // 상호 배타: 활성화 시 반대쪽 리셋
            if (isActive) resetSibling?.Invoke();

            // 피드백 상태 저장
            if (message != null)
            {
                message.Feedback = isActive ? feedbackType : null;
                try
                {
                    ChatConversation? conv;
                    lock (_convLock) conv = _currentConversation;
                    if (conv != null) _storage.Save(conv);
                }
                catch (Exception) { /* 비핵심 작업 실패 — UI 차단 방지 */ }
            }

            // 바운스 애니메이션
            var scale = (ScaleTransform)icon.RenderTransform;
            var bounce = new DoubleAnimation(1.3, 1.0, TimeSpan.FromMilliseconds(250))
            { EasingFunction = new ElasticEase { EasingMode = EasingMode.EaseOut, Oscillations = 1, Springiness = 5 } };
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, bounce);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, bounce);
        };
        return btn;
    }

    /// <summary>좋아요/싫어요 버튼을 상호 배타로 연결하여 추가</summary>
    private void AddLinkedFeedbackButtons(StackPanel actionBar, Brush btnColor, ChatMessage? message)
    {
        // resetSibling는 나중에 설정되므로 Action 래퍼로 간접 참조
        Action? resetLikeAction = null;
        Action? resetDislikeAction = null;

        var likeBtn = CreateFeedbackButton("\uE8E1", "\uEB51", "좋아요", btnColor,
            new SolidColorBrush(Color.FromRgb(0x38, 0xA1, 0x69)), message, "like",
            resetSibling: () => resetDislikeAction?.Invoke(),
            registerReset: reset => resetLikeAction = reset);
        var dislikeBtn = CreateFeedbackButton("\uE8E0", "\uEB50", "싫어요", btnColor,
            new SolidColorBrush(Color.FromRgb(0xE5, 0x3E, 0x3E)), message, "dislike",
            resetSibling: () => resetLikeAction?.Invoke(),
            registerReset: reset => resetDislikeAction = reset);

        actionBar.Children.Add(likeBtn);
        actionBar.Children.Add(dislikeBtn);
    }
}
