using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Windows.Media;
using Autodesk.Navisworks.Api;
using NavisworksTransport.Core.Services;
using NavisworksTransport.UI.WPF.ViewModels;
using NavisworksTransport.Utils;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 预计算碰撞分析对话框 - 提供排除建议
    /// </summary>
    public partial class CollisionAnalysisDialog : Window
    {
        public enum CollisionAnalysisAction
        {
            None,
            Continue,
            Regenerate,
            Cancel
        }

        private List<HotspotViewModel> _viewModels;
        public List<ModelItem> ExcludedObjects { get; private set; }
        public CollisionAnalysisAction SelectedAction { get; private set; } = CollisionAnalysisAction.None;
        
        // 使用项目中定义的预计算碰撞结果高亮类别（紫色 #9C27B0）
        private const string PrecomputedHighlightCategory = ModelHighlightHelper.PrecomputeCollisionResultsCategory;

        public CollisionAnalysisDialog(List<CollisionHotspotInfo> hotspots, int totalCollisions)
        {
            InitializeComponent();
            ExcludedObjects = new List<ModelItem>();
            Loaded += CollisionAnalysisDialog_Loaded;
            
            // 更新统计信息
            UpdateStatsText(hotspots.Count, totalCollisions);
            
            // 转换为视图模型（带序号）
            int index = 1;
            var viewModels = hotspots.Select(h => new HotspotViewModel
            {
                Index = index++,
                Object = h.Object,
                ObjectName = h.ObjectName,
                CollisionCount = h.CollisionCount,
                Percentage = h.Percentage,
                Reason = h.Reason,
                // 智能选中：碰撞次数>100 或 占比>50% 的自动勾选
                IsExcluded = h.CollisionCount > 100 || h.Percentage > 50
            }).ToList();
            
            HotspotsDataGrid.ItemsSource = viewModels;
            HotspotsDataGrid.SelectionChanged += HotspotsDataGrid_SelectionChanged;
            
            _viewModels = viewModels;
            
            // 记录自动选中结果
            int autoSelectedCount = viewModels.Count(vm => vm.IsExcluded);
            LogManager.Info($"[碰撞分析] 自动选中 {autoSelectedCount}/{viewModels.Count} 个高频碰撞物体（>100次或>50%）");
        }

        private void CollisionAnalysisDialog_Loaded(object sender, RoutedEventArgs e)
        {
            if (!TestAutomationHttpService.ShouldAutoConfirmCollisionAnalysisDialogs)
            {
                return;
            }

            Dispatcher.BeginInvoke(new Action(() =>
            {
                if (!IsLoaded || !IsVisible)
                {
                    return;
                }

                LogManager.Info("[碰撞分析] 测试自动化已接管分析窗口，自动选择继续生成");
                ModelHighlightHelper.ClearCategory(PrecomputedHighlightCategory);
                SelectedAction = CollisionAnalysisAction.Continue;
                Close();
            }), DispatcherPriority.Background);
        }

        /// <summary>
        /// 更新统计文本
        /// </summary>
        private void UpdateStatsText(int hotspotCount, int totalCollisions)
        {
            // 设置粗体数字
            CollisionCountRun.Text = totalCollisions.ToString();
            HotspotCountRun.Text = hotspotCount.ToString();
            
            // 计算预计检测时间（假设每个碰撞检测约0.5秒）
            double estimatedSeconds = totalCollisions * 0.5;
            double estimatedMinutes = estimatedSeconds / 60.0;
            
            if (estimatedMinutes >= 1)
            {
                EstimatedTimeTextBlock.Text = $"预计检测时间：{estimatedSeconds:F0}秒（{estimatedMinutes:F1}分钟）";
            }
            else
            {
                EstimatedTimeTextBlock.Text = $"预计检测时间：{estimatedSeconds:F0}秒";
            }
        }

        private void HotspotsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (HotspotsDataGrid.SelectedItem is HotspotViewModel vm)
            {
                SelectedObjectDetails.Text = $"物体: {vm.ObjectName}\n" +
                    $"碰撞次数: {vm.CollisionCount} ({vm.Percentage:F1}%)\n" +
                    $"分析: {vm.Reason}\n\n" +
                    $"建议: {(vm.IsExcluded ? "建议排除此物体" : "需要手动检查")}";
                
                // 高亮选中的物体（使用预计算高亮风格 - 紫色）
                HighlightSelectedObject(vm.Object);
            }
        }

        /// <summary>
        /// 高亮选中的物体
        /// </summary>
        private void HighlightSelectedObject(ModelItem item)
        {
            try
            {
                if (item == null) return;
                
                var items = new List<ModelItem> { item };
                // 使用预计算碰撞结果高亮类别（紫色 #9C27B0，已在ModelHighlightHelper中定义）
                ModelHighlightHelper.HighlightItems(PrecomputedHighlightCategory, items);
                
                LogManager.Debug($"[碰撞分析] 高亮显示物体: {item.DisplayName}");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[碰撞分析] 高亮物体失败: {ex.Message}");
            }
        }

        private void ActionButton_Click(object sender, RoutedEventArgs e)
        {
            // 收集选中的排除对象
            ExcludedObjects = _viewModels
                .Where(vm => vm.IsExcluded)
                .Select(vm => vm.Object)
                .ToList();
            
            // 清除预计算高亮
            ModelHighlightHelper.ClearCategory(PrecomputedHighlightCategory);
            
            if (ExcludedObjects.Count > 0)
            {
                SelectedAction = CollisionAnalysisAction.Regenerate;
                LogManager.Info($"[碰撞分析] 用户选择排除 {ExcludedObjects.Count} 个物体并重新生成");
            }
            else
            {
                SelectedAction = CollisionAnalysisAction.Continue;
                LogManager.Info("[碰撞分析] 用户选择直接继续生成（无排除对象）");
            }
            
            Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            // 清除预计算高亮
            ModelHighlightHelper.ClearCategory(PrecomputedHighlightCategory);
            
            SelectedAction = CollisionAnalysisAction.Cancel;
            Close();
        }

        private void SelectAllButton_Click(object sender, RoutedEventArgs e)
        {
            if (_viewModels == null)
            {
                return;
            }

            foreach (var viewModel in _viewModels)
            {
                viewModel.IsExcluded = true;
            }
        }

        private void ClearAllButton_Click(object sender, RoutedEventArgs e)
        {
            if (_viewModels == null)
            {
                return;
            }

            foreach (var viewModel in _viewModels)
            {
                viewModel.IsExcluded = false;
            }
        }

        /// <summary>
        /// 视图模型
        /// </summary>
        private class HotspotViewModel : System.ComponentModel.INotifyPropertyChanged
        {
            public int Index { get; set; }
            public ModelItem Object { get; set; }
            public string ObjectName { get; set; }
            public int CollisionCount { get; set; }
            public double Percentage { get; set; }
            public string Reason { get; set; }
            
            private bool _isExcluded;
            public bool IsExcluded
            {
                get => _isExcluded;
                set
                {
                    _isExcluded = value;
                    PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(nameof(IsExcluded)));
                }
            }
            
            public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        }
    }
}
