using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Threading;
using Autodesk.Navisworks.Api;

namespace NavisworksTransport.Utils
{
    /// <summary>
    /// 对话框辅助类 - 统一处理对话框 Owner 设置和置顶显示
    /// </summary>
    public static class DialogHelper
    {
        private const string TestAutomationEnvironmentVariable = "TRANSPORTPLUGIN_TEST_AUTOMATION";

        public static bool IsTestAutomationModeEnabled =>
            string.Equals(
                Environment.GetEnvironmentVariable(TestAutomationEnvironmentVariable),
                "1",
                StringComparison.OrdinalIgnoreCase);

        /// <summary>
        /// 从 UserControl 获取父窗口并设置为对话框 Owner
        /// </summary>
        /// <param name="dialog">要显示的对话框</param>
        /// <param name="userControl">当前 UserControl</param>
        /// <returns>是否成功设置 Owner</returns>
        public static bool SetOwnerFromUserControl(Window dialog, UserControl userControl)
        {
            if (dialog == null || userControl == null)
                return false;

            try
            {
                var parentWindow = Window.GetWindow(userControl);
                if (parentWindow != null)
                {
                    dialog.Owner = parentWindow;
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.Warning($"[DialogHelper] 设置 Owner 失败: {ex.Message}");
            }

            return false;
        }

        /// <summary>
        /// 在 ViewModel 中查找合适的 Owner 窗口
        /// 策略：MainWindow -> 活动窗口 -> null
        /// </summary>
        /// <returns>找到的窗口，或 null</returns>
        public static Window FindOwnerWindow()
        {
            try
            {
                // 方案1：尝试 MainWindow
                var mainWindow = System.Windows.Application.Current?.MainWindow;
                if (mainWindow != null && (mainWindow.IsVisible || mainWindow.IsLoaded))
                {
                    return mainWindow;
                }
            }
            catch (Exception ex)
            {
                LogManager.Debug($"[DialogHelper] 获取 MainWindow 失败: {ex.Message}");
            }

            // 方案2：遍历查找活动窗口
            try
            {
                if (System.Windows.Application.Current != null)
                {
                    foreach (Window window in System.Windows.Application.Current.Windows)
                    {
                        if (window.IsActive && window.IsLoaded)
                        {
                            return window;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Debug($"[DialogHelper] 遍历窗口失败: {ex.Message}");
            }

            return null;
        }

        /// <summary>
        /// 安全地设置对话框 Owner（ViewModel 场景）
        /// </summary>
        /// <param name="dialog">要设置的对话框</param>
        /// <returns>是否成功设置</returns>
        public static bool SetOwnerSafely(Window dialog)
        {
            if (dialog == null)
                return false;

            if (dialog.Owner != null)
                return true; // 已设置

            var owner = FindOwnerWindow();
            if (owner != null)
            {
                try
                {
                    dialog.Owner = owner;
                    LogManager.Debug($"[DialogHelper] 设置 Owner: {owner.Title}");
                    return true;
                }
                catch (InvalidOperationException ex)
                {
                    LogManager.Warning($"[DialogHelper] 设置 Owner 失败: {ex.Message}");
                }
            }

            return false;
        }

        /// <summary>
        /// 显示对话框（自动处理 Owner 设置）
        /// </summary>
        /// <param name="dialog">要显示的对话框</param>
        /// <param name="userControl">可选的 UserControl，用于获取 Owner</param>
        /// <returns>对话框结果</returns>
        public static bool? ShowDialog(Window dialog, UserControl userControl = null)
        {
            if (dialog == null)
                throw new ArgumentNullException(nameof(dialog));

            // 如果提供了 UserControl，优先使用它获取 Owner
            if (userControl != null)
            {
                SetOwnerFromUserControl(dialog, userControl);
            }
            else
            {
                // 否则尝试自动查找
                SetOwnerSafely(dialog);
            }

            return dialog.ShowDialog();
        }

        /// <summary>
        /// 显示 MessageBox 并确保置顶
        /// </summary>
        /// <param name="messageBoxText">消息内容</param>
        /// <param name="caption">标题</param>
        /// <param name="button">按钮类型</param>
        /// <param name="icon">图标</param>
        /// <returns>MessageBox 结果</returns>
        public static MessageBoxResult ShowMessageBox(
            string messageBoxText,
            string caption,
            MessageBoxButton button = MessageBoxButton.OK,
            MessageBoxImage icon = MessageBoxImage.Information)
        {
            var owner = FindOwnerWindow();

            if (owner != null)
            {
                return MessageBox.Show(owner, messageBoxText, caption, button, icon);
            }

            return MessageBox.Show(messageBoxText, caption, button, icon);
        }

        /// <summary>
        /// 显示自动关闭的提示窗口，避免在自动化场景中阻塞流程。
        /// </summary>
        public static void ShowAutoClosingMessageBox(
            string messageBoxText,
            string caption,
            MessageBoxImage icon = MessageBoxImage.Information,
            int autoCloseMilliseconds = 4000)
        {
            if (IsTestAutomationModeEnabled)
            {
                LogManager.Info($"[DialogHelper] 自动测试模式下跳过自动关闭提示框: {caption}");
                return;
            }

            var owner = FindOwnerWindow();

            var window = new Window
            {
                Title = caption,
                Width = 460,
                SizeToContent = SizeToContent.Height,
                ResizeMode = ResizeMode.NoResize,
                WindowStartupLocation = owner != null ? WindowStartupLocation.CenterOwner : WindowStartupLocation.CenterScreen,
                ShowInTaskbar = false,
                Topmost = true,
                Content = BuildAutoClosingDialogContent(messageBoxText, icon, autoCloseMilliseconds)
            };

            if (owner != null)
            {
                try
                {
                    window.Owner = owner;
                }
                catch (InvalidOperationException ex)
                {
                    LogManager.Warning($"[DialogHelper] 设置自动关闭提示框 Owner 失败: {ex.Message}");
                }
            }
            else
            {
                SetWin32Owner(window);
            }

            var closeTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(Math.Max(500, autoCloseMilliseconds))
            };
            closeTimer.Tick += (_, __) =>
            {
                closeTimer.Stop();
                if (window.IsVisible)
                {
                    window.Close();
                }
            };

            window.Closed += (_, __) => closeTimer.Stop();
            closeTimer.Start();
            window.Show();
        }

        /// <summary>
        /// 显示自动关闭提示框，同时通过回调更新状态栏。
        /// </summary>
        public static void ShowStatusAndDialog(
            string statusText,
            string dialogTitle,
            string dialogMessage,
            Action<string> onStatusUpdate,
            MessageBoxImage icon = MessageBoxImage.Information,
            int autoCloseMilliseconds = 4000)
        {
            onStatusUpdate?.Invoke(statusText);
            LogManager.Info($"[DialogHelper] {dialogTitle}: {dialogMessage.Replace("\n", " ")}");
            ShowAutoClosingMessageBox(dialogMessage, dialogTitle, icon, autoCloseMilliseconds);
        }

        private static FrameworkElement BuildAutoClosingDialogContent(
            string messageBoxText,
            MessageBoxImage icon,
            int autoCloseMilliseconds)
        {
            string iconGlyph;
            switch (icon)
            {
                case MessageBoxImage.Warning:
                    iconGlyph = "!";
                    break;
                case MessageBoxImage.Error:
                    iconGlyph = "X";
                    break;
                case MessageBoxImage.Question:
                    iconGlyph = "?";
                    break;
                default:
                    iconGlyph = "i";
                    break;
            }

            var root = new Grid
            {
                Margin = new Thickness(18)
            };
            root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            root.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            root.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            var iconText = new TextBlock
            {
                Text = iconGlyph,
                FontSize = 22,
                FontWeight = FontWeights.Bold,
                Margin = new Thickness(0, 0, 14, 0),
                VerticalAlignment = VerticalAlignment.Top
            };
            Grid.SetColumn(iconText, 0);
            Grid.SetRow(iconText, 0);
            root.Children.Add(iconText);

            var messageText = new TextBlock
            {
                Text = messageBoxText,
                TextWrapping = TextWrapping.Wrap,
                Margin = new Thickness(0, 2, 0, 0),
                MinWidth = 320
            };
            Grid.SetColumn(messageText, 1);
            Grid.SetRow(messageText, 0);
            root.Children.Add(messageText);

            var footerPanel = new DockPanel
            {
                Margin = new Thickness(0, 16, 0, 0),
                LastChildFill = false
            };
            Grid.SetColumn(footerPanel, 0);
            Grid.SetColumnSpan(footerPanel, 2);
            Grid.SetRow(footerPanel, 1);

            var autoCloseHint = new TextBlock
            {
                Text = $"此提示将在 {Math.Max(1, autoCloseMilliseconds / 1000)} 秒后自动关闭。",
                VerticalAlignment = VerticalAlignment.Center
            };
            DockPanel.SetDock(autoCloseHint, Dock.Left);
            footerPanel.Children.Add(autoCloseHint);

            var closeButton = new Button
            {
                Content = "确定",
                MinWidth = 72,
                Padding = new Thickness(14, 4, 14, 4),
                Margin = new Thickness(16, 0, 0, 0)
            };
            closeButton.Click += (_, __) =>
            {
                Window parentWindow = Window.GetWindow(closeButton);
                parentWindow?.Close();
            };
            DockPanel.SetDock(closeButton, Dock.Right);
            footerPanel.Children.Add(closeButton);

            root.Children.Add(footerPanel);
            return root;
        }

        /// <summary>
        /// 获取 Navisworks 主窗口句柄（Win32）
        /// </summary>
        /// <returns>窗口句柄，或 IntPtr.Zero</returns>
        public static IntPtr GetNavisworksMainWindowHandle()
        {
            try
            {
                var mainWindow = Autodesk.Navisworks.Api.Application.Gui?.MainWindow;
                if (mainWindow != null)
                {
                    return mainWindow.Handle;
                }
            }
            catch (Exception ex)
            {
                LogManager.Debug($"[DialogHelper] 获取 Navisworks 主窗口句柄失败: {ex.Message}");
            }

            return IntPtr.Zero;
        }

        /// <summary>
        /// 设置 Win32 父窗口（用于需要强制置顶到 Navisworks 主窗口的场景）
        /// </summary>
        /// <param name="dialog">对话框</param>
        /// <returns>是否成功</returns>
        public static bool SetWin32Owner(Window dialog)
        {
            if (dialog == null)
                return false;

            var handle = GetNavisworksMainWindowHandle();
            if (handle == IntPtr.Zero)
                return false;

            try
            {
                var helper = new WindowInteropHelper(dialog);
                helper.Owner = handle;
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Warning($"[DialogHelper] 设置 Win32 Owner 失败: {ex.Message}");
            }

            return false;
        }
    }
}
