using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Autodesk.Navisworks.Api;
using NavisworksTransport.Utils;
using NavisworksTransport.Utils.CoordinateSystem;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 显示选中模型元素包围盒信息的窗口
    /// </summary>
    public partial class ModelItemBoundsWindow : Window
    {
        #region 属性

        /// <summary>元素名称</summary>
        public string ElementName { get; set; } = "未选择元素";

        /// <summary>X方向尺寸</summary>
        public double SizeX { get; set; }

        /// <summary>Y方向尺寸</summary>
        public double SizeY { get; set; }

        /// <summary>Z方向尺寸</summary>
        public double SizeZ { get; set; }

        /// <summary>中心点X坐标</summary>
        public double CenterX { get; set; }

        /// <summary>中心点Y坐标</summary>
        public double CenterY { get; set; }

        /// <summary>中心点Z坐标</summary>
        public double CenterZ { get; set; }

        /// <summary>宿主包围盒顶面中心点X坐标</summary>
        public double HostTopCenterX { get; set; }

        /// <summary>宿主包围盒顶面中心点Y坐标</summary>
        public double HostTopCenterY { get; set; }

        /// <summary>宿主包围盒顶面中心点Z坐标</summary>
        public double HostTopCenterZ { get; set; }

        /// <summary>宿主包围盒底面中心点X坐标</summary>
        public double HostBottomCenterX { get; set; }

        /// <summary>宿主包围盒底面中心点Y坐标</summary>
        public double HostBottomCenterY { get; set; }

        /// <summary>宿主包围盒底面中心点Z坐标</summary>
        public double HostBottomCenterZ { get; set; }

        /// <summary>对象姿态语义顶面中心点X坐标</summary>
        public double OrientedTopCenterX { get; set; }

        /// <summary>对象姿态语义顶面中心点Y坐标</summary>
        public double OrientedTopCenterY { get; set; }

        /// <summary>对象姿态语义顶面中心点Z坐标</summary>
        public double OrientedTopCenterZ { get; set; }

        /// <summary>对象姿态语义底面中心点X坐标</summary>
        public double OrientedBottomCenterX { get; set; }

        /// <summary>对象姿态语义底面中心点Y坐标</summary>
        public double OrientedBottomCenterY { get; set; }

        /// <summary>对象姿态语义底面中心点Z坐标</summary>
        public double OrientedBottomCenterZ { get; set; }

        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public ModelItemBoundsWindow()
        {
            try
            {
                InitializeComponent();
                DataContext = this;
                RefreshBoundsInfo();
            }
            catch (Exception ex)
            {
                LogManager.Error($"包围盒信息窗口初始化失败: {ex.Message}", ex);
                MessageBox.Show($"包围盒信息窗口初始化失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 刷新包围盒信息
        /// </summary>
        public void RefreshBoundsInfo()
        {
            try
            {
                var doc = Autodesk.Navisworks.Api.Application.ActiveDocument;
                if (doc == null)
                {
                    ElementName = "未找到活动文档";
                    ClearBoundsData();
                    return;
                }

                var selectedItems = doc.CurrentSelection.SelectedItems;
                if (selectedItems.Count == 0)
                {
                    ElementName = "未选择任何元素";
                    ClearBoundsData();
                    return;
                }

                // 获取第一个选中的元素
                var item = selectedItems[0];
                if (item == null)
                {
                    ElementName = "无法获取选中元素";
                    ClearBoundsData();
                    return;
                }

                // 获取元素名称
                ElementName = item.DisplayName ?? "未命名元素";

                // 获取包围盒
                Autodesk.Navisworks.Api.BoundingBox3D bounds = item.BoundingBox();
                if (bounds == null)
                {
                    ElementName = "无法获取包围盒信息";
                    ClearBoundsData();
                    return;
                }

                // 计算尺寸
                SizeX = bounds.Max.X - bounds.Min.X;
                SizeY = bounds.Max.Y - bounds.Min.Y;
                SizeZ = bounds.Max.Z - bounds.Min.Z;

                // 计算中心点
                CenterX = (bounds.Min.X + bounds.Max.X) / 2.0;
                CenterY = (bounds.Min.Y + bounds.Max.Y) / 2.0;
                CenterZ = (bounds.Min.Z + bounds.Max.Z) / 2.0;

                HostCoordinateAdapter adapter = CoordinateSystemManager.Instance.CreateHostAdapter();

                Point3D hostBottomCenter = ModelItemTransformHelper.GetHostBottomAnchorPoint(bounds, adapter);
                double hostHeight = ModelItemTransformHelper.GetHostHeight(bounds, adapter);
                Point3D hostTopCenter = new Point3D(
                    hostBottomCenter.X + adapter.HostUpVector.X * hostHeight,
                    hostBottomCenter.Y + adapter.HostUpVector.Y * hostHeight,
                    hostBottomCenter.Z + adapter.HostUpVector.Z * hostHeight);

                HostBottomCenterX = hostBottomCenter.X;
                HostBottomCenterY = hostBottomCenter.Y;
                HostBottomCenterZ = hostBottomCenter.Z;
                HostTopCenterX = hostTopCenter.X;
                HostTopCenterY = hostTopCenter.Y;
                HostTopCenterZ = hostTopCenter.Z;

                Point3D orientedBottomCenter = ModelItemTransformHelper.GetStableBottomAnchorPoint(bounds, item.Transform);
                Vector3D objectUp = ModelItemTransformHelper.GetUpDirectionFromTransform(item.Transform);
                Vector3D localSize = ModelItemTransformHelper.EstimateLocalBoxSize(bounds, item.Transform);
                Point3D orientedTopCenter = new Point3D(
                    orientedBottomCenter.X + objectUp.X * localSize.Z,
                    orientedBottomCenter.Y + objectUp.Y * localSize.Z,
                    orientedBottomCenter.Z + objectUp.Z * localSize.Z);

                OrientedBottomCenterX = orientedBottomCenter.X;
                OrientedBottomCenterY = orientedBottomCenter.Y;
                OrientedBottomCenterZ = orientedBottomCenter.Z;
                OrientedTopCenterX = orientedTopCenter.X;
                OrientedTopCenterY = orientedTopCenter.Y;
                OrientedTopCenterZ = orientedTopCenter.Z;
            }
            catch (Exception ex)
            {
                LogManager.Error($"获取包围盒信息失败: {ex.Message}", ex);
                ElementName = $"获取失败: {ex.Message}";
                ClearBoundsData();
            }
            finally
            {
                // 通知UI更新
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 清空包围盒数据
        /// </summary>
        private void ClearBoundsData()
        {
            SizeX = SizeY = SizeZ = 0;
            CenterX = CenterY = CenterZ = 0;
            HostTopCenterX = HostTopCenterY = HostTopCenterZ = 0;
            HostBottomCenterX = HostBottomCenterY = HostBottomCenterZ = 0;
            OrientedTopCenterX = OrientedTopCenterY = OrientedTopCenterZ = 0;
            OrientedBottomCenterX = OrientedBottomCenterY = OrientedBottomCenterZ = 0;
        }

        /// <summary>
        /// 通知所有属性变更
        /// </summary>
        private void OnPropertyChanged()
        {
            // 重新设置 DataContext 触发刷新
            DataContext = null;
            DataContext = this;
        }

        /// <summary>
        /// 刷新按钮点击
        /// </summary>
        private void OnRefreshClick(object sender, RoutedEventArgs e)
        {
            RefreshBoundsInfo();
        }

        /// <summary>
        /// 关闭按钮点击
        /// </summary>
        private void OnCloseClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 复制中心点坐标
        /// </summary>
        private void OnCopyCenterClick(object sender, RoutedEventArgs e)
        {
            string coordinate = string.Format("{0:0.000}, {1:0.000}, {2:0.000}", CenterX, CenterY, CenterZ);
            bool success = ClipboardHelper.TrySetText(coordinate, "元素包围盒信息");
            ShowButtonFeedback(CopyCenterButton, success);
        }

        /// <summary>
        /// 复制顶面中心坐标
        /// </summary>
        private void OnCopyTopCenterClick(object sender, RoutedEventArgs e)
        {
            string coordinate = string.Format("{0:0.000}, {1:0.000}, {2:0.000}", HostTopCenterX, HostTopCenterY, HostTopCenterZ);
            bool success = ClipboardHelper.TrySetText(coordinate, "元素包围盒信息");
            ShowButtonFeedback(CopyTopButton, success);
        }

        /// <summary>
        /// 复制底面中心坐标
        /// </summary>
        private void OnCopyBottomCenterClick(object sender, RoutedEventArgs e)
        {
            string coordinate = string.Format("{0:0.000}, {1:0.000}, {2:0.000}", HostBottomCenterX, HostBottomCenterY, HostBottomCenterZ);
            bool success = ClipboardHelper.TrySetText(coordinate, "元素包围盒信息");
            ShowButtonFeedback(CopyBottomButton, success);
        }

        private void OnCopyOrientedTopCenterClick(object sender, RoutedEventArgs e)
        {
            string coordinate = string.Format("{0:0.000}, {1:0.000}, {2:0.000}", OrientedTopCenterX, OrientedTopCenterY, OrientedTopCenterZ);
            bool success = ClipboardHelper.TrySetText(coordinate, "元素包围盒信息");
            ShowButtonFeedback(CopyOrientedTopButton, success);
        }

        private void OnCopyOrientedBottomCenterClick(object sender, RoutedEventArgs e)
        {
            string coordinate = string.Format("{0:0.000}, {1:0.000}, {2:0.000}", OrientedBottomCenterX, OrientedBottomCenterY, OrientedBottomCenterZ);
            bool success = ClipboardHelper.TrySetText(coordinate, "元素包围盒信息");
            ShowButtonFeedback(CopyOrientedBottomButton, success);
        }

        /// <summary>
        /// 显示按钮点击反馈
        /// </summary>
        private void ShowButtonFeedback(Button button, bool success)
        {
            if (button == null) return;
            
            var originalBackground = button.Background;
            var originalBorderBrush = button.BorderBrush;
            
            if (success)
            {
                button.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(76, 175, 80));
                button.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(56, 142, 60));
            }
            else
            {
                button.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(244, 67, 54));
                button.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(211, 47, 47));
            }
            
            var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(800) };
            timer.Tick += (s, e) =>
            {
                timer.Stop();
                button.Background = originalBackground;
                button.BorderBrush = originalBorderBrush;
            };
            timer.Start();
        }
    }
}
