using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Serilog;
using XplorePlane.ViewModels;

namespace XplorePlane.Views
{
    public partial class OperatorToolboxView : UserControl
    {
        public const string DragFormat = "PipelineOperatorKey";

        private Point _dragStartPoint;
        private bool _isDragging;

        public OperatorToolboxView()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            ToolboxListBox.PreviewMouseLeftButtonDown += OnPreviewMouseDown;
            ToolboxListBox.PreviewMouseMove += OnPreviewMouseMove;
            Log.Debug("OperatorToolboxView 原生拖拽源已注册, DataContext={Type}",
                DataContext?.GetType().Name);
        }

        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            _dragStartPoint = e.GetPosition(null);
            _isDragging = false;
        }

        private void OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;

            var pos = e.GetPosition(null);
            var diff = pos - _dragStartPoint;

            if (!_isDragging
                && (System.Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance
                 || System.Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
            {
                _isDragging = true;

                // 从鼠标位置 HitTest 找到 OperatorDescriptor
                var hitResult = System.Windows.Media.VisualTreeHelper.HitTest(
                    ToolboxListBox, e.GetPosition(ToolboxListBox));

                OperatorDescriptor? descriptor = null;
                var node = hitResult?.VisualHit as DependencyObject;
                while (node != null)
                {
                    if (node is FrameworkElement fe && fe.DataContext is OperatorDescriptor d)
                    {
                        descriptor = d;
                        break;
                    }
                    node = System.Windows.Media.VisualTreeHelper.GetParent(node);
                }

                if (descriptor == null)
                {
                    Log.Warning("拖拽初始化失败：HitTest 未命中算子项");
                    return;
                }

                Log.Information("开始拖拽算子：{OperatorKey} ({DisplayName})", descriptor.Key, descriptor.DisplayName);
                var data = new DataObject(DragFormat, descriptor.Key);
                DragDrop.DoDragDrop(ToolboxListBox, data, DragDropEffects.Copy);
            }
        }
    }
}
