using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Autodesk.Navisworks.Api;
using NavisworksTransport.Core.Config;
using NavisworksTransport.Core.Models;
using NavisworksTransport.Utils;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 路径配置对话框
    /// </summary>
    public partial class PathConfigDialog : Window
    {
        private List<ModelItem> _detectionItems;
        private ModelItem _selectedObject;

        public PathConfigDialog(CollisionDetectionConfig existingConfig = null)
        {
            InitializeComponent();

            _detectionItems = new List<ModelItem>();
            _selectedObject = null;

            // 从系统配置读取虚拟物体默认值
            var systemConfig = ConfigManager.Instance.Current;
            txtObjectLength.Text = systemConfig.PathEditing.ObjectLengthMeters.ToString("F2");
            txtObjectWidth.Text = systemConfig.PathEditing.ObjectWidthMeters.ToString("F2");
            txtObjectHeight.Text = systemConfig.PathEditing.ObjectHeightMeters.ToString("F2");

            // 设置初始状态（在 InitializeComponent 之后，避免触发 Checked 事件）
            rbVirtualObject.IsChecked = true;

            // 如果有现有配置，加载它（会覆盖上面的默认值）
            if (existingConfig != null)
            {
                LoadExistingConfig(existingConfig);
            }
        }

        /// <summary>
        /// 获取配置
        /// </summary>
        public PathConfigResult GetResult()
        {
            var result = new PathConfigResult
            {
                IsVirtualObject = rbVirtualObject.IsChecked == true,
                VirtualObjectLength = double.Parse(txtObjectLength.Text),
                VirtualObjectWidth = double.Parse(txtObjectWidth.Text),
                VirtualObjectHeight = double.Parse(txtObjectHeight.Text),
                MovingObjectId = _selectedObject?.ToString(),
                MovingObjectName = _selectedObject?.DisplayName,
                DetectionItems = _detectionItems.Select(i => i.ToString()).ToList(),
                DetectAllObjects = rbDetectAll.IsChecked == true,
                UseOverrideConfig = cbOverrideConfig.IsChecked == true
            };

            if (result.UseOverrideConfig)
            {
                // 用户输入为米单位，转换为模型单位存储
                    double detectionGapMeters = double.Parse(txtDetectionGap.Text);
                    result.ConfigOverride = new CollisionDetectionConfig
                    {
                        FrameRate = int.Parse(txtFrameRate.Text),
                        DurationSeconds = double.Parse(txtDuration.Text),
                        DetectionTolerance = detectionGapMeters * UnitsConverter.GetMetersToUnitsConversionFactor()
                    };
            }

            return result;
        }

        /// <summary>
        /// 加载现有配置
        /// </summary>
        private void LoadExistingConfig(CollisionDetectionConfig config)
        {
            if (config == null) return;

            txtObjectLength.Text = config.VirtualObjectLength.ToString("F2");
            txtObjectWidth.Text = config.VirtualObjectWidth.ToString("F2");
            txtObjectHeight.Text = config.VirtualObjectHeight.ToString("F2");
            txtFrameRate.Text = config.FrameRate.ToString();
            txtDuration.Text = config.DurationSeconds.ToString("F2");
            // 模型单位转换为米单位显示
            txtDetectionGap.Text = (config.DetectionTolerance * UnitsConverter.GetUnitsToMetersConversionFactor()).ToString("F2");
        }

        /// <summary>
        /// 虚拟物体选中
        /// </summary>
        private void rbVirtualObject_Checked(object sender, RoutedEventArgs e)
        {
            borderVirtualObject.Visibility = Visibility.Visible;
            borderRealObject.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 真实物物体选中
        /// </summary>
        private void rbRealObject_Checked(object sender, RoutedEventArgs e)
        {
            borderVirtualObject.Visibility = Visibility.Collapsed;
            borderRealObject.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 从视图选择物体
        /// </summary>
        private void btnSelectFromView_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取当前选中的物体
                var doc = Autodesk.Navisworks.Api.Application.ActiveDocument;
                if (doc == null)
                {
                    MessageBox.Show("没有打开的文档", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var selection = doc.CurrentSelection;
                if (selection == null || selection.IsEmpty)
                {
                    MessageBox.Show("请先在视图或选择树中选择物体", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var selectedItems = selection.SelectedItems;
                if (selectedItems.Count > 1)
                {
                    MessageBox.Show("请只选择一个物体", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                _selectedObject = selectedItems.First;
                txtSelectedObject.Text = _selectedObject.DisplayName;
                txtObjectId.Text = _selectedObject.ToString();

                LogManager.Info($"[路径配置] 已选择物体: {_selectedObject.DisplayName}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择物体失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                LogManager.Error($"[路径配置] 选择物体失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 选择检测项
        /// </summary>
        private void btnSelectDetectionItems_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var doc = Autodesk.Navisworks.Api.Application.ActiveDocument;
                if (doc == null)
                {
                    MessageBox.Show("没有打开的文档", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var selection = doc.CurrentSelection;
                if (selection == null || selection.IsEmpty)
                {
                    MessageBox.Show("请先在视图或选择树中选择检测项", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                _detectionItems.Clear();
                var selectedItems = selection.SelectedItems;
                foreach (var item in selectedItems)
                {
                    _detectionItems.Add(item);
                }

                txtDetectionItemCount.Text = _detectionItems.Count.ToString();

                LogManager.Info($"[路径配置] 已选择 {_detectionItems.Count} 个检测项");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择检测项失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                LogManager.Error($"[路径配置] 选择检测项失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 启用配置覆盖
        /// </summary>
        private void cbOverrideConfig_Checked(object sender, RoutedEventArgs e)
        {
            gridOverrideConfig.IsEnabled = true;
        }

        /// <summary>
        /// 禁用配置覆盖
        /// </summary>
        private void cbOverrideConfig_Unchecked(object sender, RoutedEventArgs e)
        {
            gridOverrideConfig.IsEnabled = false;
        }

        /// <summary>
        /// 确定
        /// </summary>
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 验证虚拟物体参数
                if (rbVirtualObject.IsChecked == true)
                {
                    if (!double.TryParse(txtObjectLength.Text, out var length) || length <= 0)
                    {
                        MessageBox.Show("请输入有效的物体长度", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (!double.TryParse(txtObjectWidth.Text, out var width) || width <= 0)
                    {
                        MessageBox.Show("请输入有效的物体宽度", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (!double.TryParse(txtObjectHeight.Text, out var height) || height <= 0)
                    {
                        MessageBox.Show("请输入有效的物体高度", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }

                // 验证真实物体选择
                if (rbRealObject.IsChecked == true && _selectedObject == null)
                {
                    MessageBox.Show("请选择一个真实物体", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 验证配置覆盖参数
                if (cbOverrideConfig.IsChecked == true)
                {
                    if (!int.TryParse(txtFrameRate.Text, out var frameRate) || frameRate <= 0)
                    {
                        MessageBox.Show("请输入有效的帧率", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (!double.TryParse(txtDuration.Text, out var duration) || duration <= 0)
                    {
                        MessageBox.Show("请输入有效的动画时长", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    if (!double.TryParse(txtDetectionGap.Text, out var gap) || gap <= 0)
                    {
                        MessageBox.Show("请输入有效的检测间隙", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }

                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"验证失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }

    /// <summary>
    /// 路径配置结果
    /// </summary>
    public class PathConfigResult
    {
        public bool IsVirtualObject { get; set; }
        public double VirtualObjectLength { get; set; }
        public double VirtualObjectWidth { get; set; }
        public double VirtualObjectHeight { get; set; }
        public string MovingObjectId { get; set; }
        public string MovingObjectName { get; set; }
        public List<string> DetectionItems { get; set; }
        public bool DetectAllObjects { get; set; }
        public bool UseOverrideConfig { get; set; }
        public CollisionDetectionConfig ConfigOverride { get; set; }
    }
}