using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using NavisworksTransport.UI.WPF.ViewModels;
using NavisworksTransport.Commands;
using CollisionReportScreenshot = NavisworksTransport.Commands.CollisionReportScreenshot;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 碰撞检测报告对话框
    /// </summary>
    public partial class CollisionReportDialog : Window
    {
        #region 私有字段

        /// <summary>
        /// ViewModel实例
        /// </summary>
        private CollisionReportViewModel _viewModel;

        /// <summary>
        /// 当前显示的碰撞报告窗口实例（单例模式）
        /// </summary>
        private static CollisionReportDialog _currentInstance = null;

        /// <summary>
        /// 用于线程同步的锁对象
        /// </summary>
        private static readonly object _lock = new object();

        #endregion

        #region 构造函数

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public CollisionReportDialog()
        {
            InitializeComponent();
            InitializeViewModel();
            LogManager.Info("碰撞报告对话框已创建");
        }

        /// <summary>
        /// 带报告数据的构造函数
        /// </summary>
        /// <param name="reportResult">报告数据</param>
        public CollisionReportDialog(CollisionReportResult reportResult) : this()
        {
            if (reportResult != null)
            {
                _viewModel.InitializeReport(reportResult);
                LogManager.Info($"碰撞报告对话框已创建并初始化数据，包含 {reportResult.TotalCollisions} 个碰撞");
            }
        }

        #endregion

        #region 初始化方法

        /// <summary>
        /// 初始化ViewModel并设置数据上下文
        /// </summary>
        private void InitializeViewModel()
        {
            try
            {
                _viewModel = new CollisionReportViewModel();
                this.DataContext = _viewModel;
                LogManager.Debug("碰撞报告对话框ViewModel初始化成功");
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化碰撞报告对话框ViewModel失败: {ex.Message}");
                MessageBox.Show($"初始化报告窗口失败: {ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        #region 事件处理方法

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private async void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LogManager.Info("用户关闭碰撞报告对话框，正在自动导出最终报告...");
                await AutoExportReportAsync();
                this.Close();
            }
            catch (Exception ex)
            {
                LogManager.Error($"关闭碰撞报告对话框失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 窗口关闭事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        protected override void OnClosed(EventArgs e)
        {
            try
            {
                // 恢复运动物体到原始状态（查看碰撞前保存的状态）
                if (_viewModel != null)
                {
                    _viewModel.RestoreAnimatedObjectToOriginalState();
                }
                
                // 清理资源
                if (_viewModel != null)
                {
                    // 如果ViewModel有清理方法，可以在这里调用
                    _viewModel = null;
                }

                // 清除静态实例引用
                lock (_lock)
                {
                    if (_currentInstance == this)
                    {
                        _currentInstance = null;
                        LogManager.Info("碰撞报告对话框实例已从单例缓存中移除");
                    }
                }

                LogManager.Debug("碰撞报告对话框资源已清理");
            }
            catch (Exception ex)
            {
                LogManager.Error($"清理碰撞报告对话框资源失败: {ex.Message}");
            }
            finally
            {
                base.OnClosed(e);
            }
        }

        private async System.Threading.Tasks.Task AutoExportReportAsync()
        {
            if (_viewModel != null)
            {
                await _viewModel.AutoExportReportAsync();
            }
        }

        /// <summary>
        /// 窗口加载事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            
            try
            {
                // 设置窗口图标（如果需要）
                // this.Icon = ...

                // 设置窗口焦点
                this.Focus();
                
                LogManager.Debug("碰撞报告对话框初始化完成");
            }
            catch (Exception ex)
            {
                LogManager.Error($"碰撞报告对话框初始化失败: {ex.Message}");
            }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 更新报告数据
        /// </summary>
        /// <param name="reportResult">新的报告数据</param>
        public void UpdateReport(CollisionReportResult reportResult)
        {
            try
            {
                if (_viewModel != null && reportResult != null)
                {
                    _viewModel.InitializeReport(reportResult);
                    LogManager.Info($"碰撞报告对话框数据已更新，包含 {reportResult.TotalCollisions} 个碰撞");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"更新碰撞报告数据失败: {ex.Message}");
                MessageBox.Show($"更新报告数据失败: {ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 获取ViewModel实例
        /// </summary>
        /// <returns>ViewModel实例</returns>
        public CollisionReportViewModel GetViewModel()
        {
            return _viewModel;
        }

        /// <summary>
        /// 显示对话框并返回结果
        /// </summary>
        /// <param name="owner">父窗口</param>
        /// <returns>对话框结果</returns>
        public bool? ShowDialogWithOwner(Window owner = null)
        {
            try
            {
                if (owner != null)
                {
                    this.Owner = owner;
                }

                LogManager.Info("显示碰撞报告对话框");
                return base.ShowDialog();
            }
            catch (Exception ex)
            {
                LogManager.Error($"显示碰撞报告对话框失败: {ex.Message}");
                MessageBox.Show($"显示报告对话框失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }

        /// <summary>
        /// 激活并显示已存在的窗口
        /// </summary>
        private void ActivateWindow()
        {
            try
            {
                // 如果窗口被最小化，则恢复
                if (this.WindowState == WindowState.Minimized)
                {
                    this.WindowState = WindowState.Normal;
                }

                // 激活并前置窗口
                this.Activate();
                this.Topmost = true;  // 暂时置顶
                this.Topmost = false; // 然后取消置顶，但保持前置

                LogManager.Info("碰撞报告对话框已激活并前置显示");
            }
            catch (Exception ex)
            {
                LogManager.Error($"激活碰撞报告对话框失败: {ex.Message}");
            }
        }

        #endregion

        #region 截图相关事件处理

        /// <summary>
        /// 缩略图点击事件 - 切换主图显示
        /// </summary>
        private void OnThumbnailClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                if (sender is Border border && border.DataContext is CollisionReportScreenshot screenshot)
                {
                    _viewModel?.SelectScreenshotCommand?.Execute(screenshot);
                    LogManager.Debug($"切换截图: {screenshot.FilePath}");
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"切换截图失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加截图按钮点击事件
        /// </summary>
        private void OnAddScreenshotClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                _viewModel?.AddScreenshotCommand?.Execute(null);
            }
            catch (Exception ex)
            {
                LogManager.Error($"添加截图失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除截图按钮点击事件 - 删除当前选中的截图
        /// </summary>
        private void OnDeleteScreenshotClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                // 删除当前选中的截图
                if (_viewModel?.SelectedScreenshot != null)
                {
                    _viewModel?.DeleteScreenshotCommand?.Execute(_viewModel.SelectedScreenshot);
                }
                else if (_viewModel?.Screenshots?.Count > 0)
                {
                    // 如果没有选中，删除最后一张
                    var lastScreenshot = _viewModel.Screenshots.LastOrDefault();
                    if (lastScreenshot != null)
                    {
                        _viewModel?.DeleteScreenshotCommand?.Execute(lastScreenshot);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"删除截图失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 碰撞详情项目单击事件处理 - 聚焦到被撞对象
        /// </summary>
        private void OnCollisionItemClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                if (_viewModel == null) return;

                // 获取点击的 Border 元素
                if (sender is Border border && border.DataContext is CollisionReportItem collisionItem)
                {
                    // 高亮并聚焦到被撞对象
                    _viewModel.HighlightAndFocusCollisionItem(collisionItem);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CollisionReportDialog] 处理碰撞详情单击失败: {ex.Message}", ex);
            }
        }

        #endregion

        #region 静态工厂方法

        /// <summary>
        /// 创建并显示碰撞报告对话框（单例模式）
        /// </summary>
        /// <param name="reportResult">报告数据</param>
        /// <param name="owner">父窗口</param>
        /// <returns>对话框实例</returns>
        public static CollisionReportDialog ShowReport(CollisionReportResult reportResult, Window owner = null)
        {
            try
            {
                lock (_lock)
                {
                    // 如果当前已有实例且仍然打开，则更新数据并激活窗口
                    if (_currentInstance != null)
                    {
                        try
                        {
                            // 检查窗口是否仍然有效
                            if (_currentInstance.IsLoaded && _currentInstance.IsVisible)
                            {
                                LogManager.Info("检测到已存在的碰撞报告窗口，更新数据并激活窗口");

                                // 更新数据
                                if (reportResult != null)
                                {
                                    _currentInstance.UpdateReport(reportResult);
                                }

                                // 激活窗口
                                _currentInstance.ActivateWindow();

                                return _currentInstance;
                            }
                            else
                            {
                                // 窗口已关闭，清除引用
                                _currentInstance = null;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.Warning($"检查现有窗口状态时出现异常: {ex.Message}，将创建新窗口");
                            _currentInstance = null;
                        }
                    }

                    // 创建新的对话框实例
                    var dialog = new CollisionReportDialog(reportResult);

                    if (owner != null)
                    {
                        dialog.Owner = owner;
                    }

                    // 设置为当前实例
                    _currentInstance = dialog;

                    // 异步显示对话框，避免阻塞UI
                    dialog.Show();

                    LogManager.Info("新的碰撞报告对话框已显示");
                    return dialog;
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"显示碰撞报告对话框失败: {ex.Message}");
                MessageBox.Show($"显示报告对话框失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return null;
            }
        }

        /// <summary>
        /// 创建并显示模态碰撞报告对话框
        /// </summary>
        /// <param name="reportResult">报告数据</param>
        /// <param name="owner">父窗口</param>
        /// <returns>对话框结果</returns>
        public static bool? ShowReportModal(CollisionReportResult reportResult, Window owner = null)
        {
            try
            {
                var dialog = new CollisionReportDialog(reportResult);
                return dialog.ShowDialogWithOwner(owner);
            }
            catch (Exception ex)
            {
                LogManager.Error($"显示模态碰撞报告对话框失败: {ex.Message}");
                MessageBox.Show($"显示报告对话框失败: {ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }

        #endregion
    }
}
