namespace NavisworksTransport.Core.UIUpdate
{
    /// <summary>
    /// MainPlugin UI协调器
    /// 统一管理MainPlugin中的UI更新操作，替代直接的UI线程调用
    /// </summary>
    public class MainPluginUICoordinator : IDisposable
    {
        #region 字段和属性

        private readonly IUIUpdateService _uiUpdateService;
        private readonly Dictionary<string, Control> _registeredControls;
        private volatile bool _isDisposed = false;

        /// <summary>
        /// UI更新服务实例
        /// </summary>
        public IUIUpdateService UIUpdateService => _uiUpdateService;

        /// <summary>
        /// 是否已初始化
        /// </summary>
        public bool IsInitialized { get; private set; }

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化MainPlugin UI协调器
        /// </summary>
        /// <param name="uiUpdateService">UI更新服务</param>
        public MainPluginUICoordinator(IUIUpdateService uiUpdateService = null)
        {
            _uiUpdateService = uiUpdateService ?? new UIUpdateService(UIUpdateServiceConfiguration.Default());
            _registeredControls = new Dictionary<string, Control>();

            LogManager.Info("[MainPluginUICoordinator] UI协调器已创建");
        }

        #endregion

        #region 初始化和清理

        /// <summary>
        /// 初始化UI协调器
        /// </summary>
        public async Task InitializeAsync()
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(nameof(MainPluginUICoordinator));
            }

            if (IsInitialized)
            {
                LogManager.Warning("[MainPluginUICoordinator] UI协调器已经初始化，跳过重复初始化");
                return;
            }

            try
            {
                LogManager.Info("[MainPluginUICoordinator] 开始初始化UI协调器");

                // 初始化UI更新服务
                await _uiUpdateService.InitializeAsync();

                // 订阅UI更新服务事件
                SubscribeToUIUpdateServiceEvents();

                IsInitialized = true;
                LogManager.Info("[MainPluginUICoordinator] UI协调器初始化完成");
            }
            catch (Exception ex)
            {
                LogManager.Error("[MainPluginUICoordinator] 初始化UI协调器失败", ex);
                throw;
            }
        }

        /// <summary>
        /// 注册控件到协调器
        /// </summary>
        /// <param name="name">控件名称</param>
        /// <param name="control">控件实例</param>
        public void RegisterControl(string name, Control control)
        {
            if (string.IsNullOrEmpty(name) || control == null)
            {
                return;
            }

            _registeredControls[name] = control;
            LogManager.Debug($"[MainPluginUICoordinator] 注册控件: {name} ({control.GetType().Name})");
        }

        /// <summary>
        /// 批量注册控件
        /// </summary>
        /// <param name="controls">控件字典</param>
        public void RegisterControls(Dictionary<string, Control> controls)
        {
            if (controls == null)
            {
                return;
            }

            foreach (var kvp in controls)
            {
                RegisterControl(kvp.Key, kvp.Value);
            }
        }

        /// <summary>
        /// 取消注册控件
        /// </summary>
        /// <param name="name">控件名称</param>
        public void UnregisterControl(string name)
        {
            if (_registeredControls.ContainsKey(name))
            {
                _registeredControls.Remove(name);
                LogManager.Debug($"[MainPluginUICoordinator] 取消注册控件: {name}");
            }
        }

        #endregion

        #region 核心UI更新方法

        /// <summary>
        /// 更新控件属性（线程安全）
        /// </summary>
        /// <param name="controlName">控件名称</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="value">新值</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> UpdateControlPropertyAsync(string controlName, string propertyName, object value, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            if (!_registeredControls.TryGetValue(controlName, out var control))
            {
                return UIUpdateResult.Failure($"未找到控件: {controlName}");
            }

            var update = UIUpdateFactory.UpdateProperty(control, propertyName, value, priority);
            return await _uiUpdateService.ExecuteUpdateAsync(update);
        }

        /// <summary>
        /// 更新控件文本
        /// </summary>
        /// <param name="controlName">控件名称</param>
        /// <param name="text">新文本</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> UpdateControlTextAsync(string controlName, string text, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            return await UpdateControlPropertyAsync(controlName, "Text", text, priority);
        }

        /// <summary>
        /// 更新控件启用状态
        /// </summary>
        /// <param name="controlName">控件名称</param>
        /// <param name="enabled">是否启用</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> UpdateControlEnabledAsync(string controlName, bool enabled, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            return await UpdateControlPropertyAsync(controlName, "Enabled", enabled, priority);
        }

        /// <summary>
        /// 更新控件可见性
        /// </summary>
        /// <param name="controlName">控件名称</param>
        /// <param name="visible">是否可见</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> UpdateControlVisibilityAsync(string controlName, bool visible, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            return await UpdateControlPropertyAsync(controlName, "Visible", visible, priority);
        }

        /// <summary>
        /// 批量更新控件属性
        /// </summary>
        /// <param name="updates">更新操作字典 (控件名称 -> (属性名, 新值))</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>批量更新结果</returns>
        public async Task<UIBatchUpdateResult> UpdateControlsAsync(Dictionary<string, Dictionary<string, object>> updates, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            var updateOperations = new List<IUIUpdate>();

            foreach (var controlUpdate in updates)
            {
                var controlName = controlUpdate.Key;
                var properties = controlUpdate.Value;

                if (!_registeredControls.TryGetValue(controlName, out var control))
                {
                    LogManager.Warning($"[MainPluginUICoordinator] 未找到控件: {controlName}");
                    continue;
                }

                foreach (var property in properties)
                {
                    updateOperations.Add(UIUpdateFactory.UpdateProperty(control, property.Key, property.Value, priority));
                }
            }

            return await _uiUpdateService.ExecuteBatchUpdateAsync(updateOperations);
        }

        #endregion

        #region ListView专用操作

        /// <summary>
        /// 向ListView添加项目
        /// </summary>
        /// <param name="listViewName">ListView名称</param>
        /// <param name="item">要添加的项目</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> AddListViewItemAsync(string listViewName, ListViewItem item, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            if (!_registeredControls.TryGetValue(listViewName, out var control) || !(control is ListView listView))
            {
                return UIUpdateResult.Failure($"未找到ListView控件: {listViewName}");
            }

            var update = UIUpdateFactory.AddToCollection(listView, item, priority);
            return await _uiUpdateService.ExecuteUpdateAsync(update);
        }

        /// <summary>
        /// 从ListView删除项目
        /// </summary>
        /// <param name="listViewName">ListView名称</param>
        /// <param name="item">要删除的项目</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> RemoveListViewItemAsync(string listViewName, ListViewItem item, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            if (!_registeredControls.TryGetValue(listViewName, out var control) || !(control is ListView listView))
            {
                return UIUpdateResult.Failure($"未找到ListView控件: {listViewName}");
            }

            var update = UIUpdateFactory.RemoveFromCollection(listView, item, priority);
            return await _uiUpdateService.ExecuteUpdateAsync(update);
        }

        /// <summary>
        /// 清空ListView
        /// </summary>
        /// <param name="listViewName">ListView名称</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> ClearListViewAsync(string listViewName, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            if (!_registeredControls.TryGetValue(listViewName, out var control) || !(control is ListView listView))
            {
                return UIUpdateResult.Failure($"未找到ListView控件: {listViewName}");
            }

            var update = UIUpdateFactory.ClearCollection(listView, priority);
            return await _uiUpdateService.ExecuteUpdateAsync(update);
        }

        /// <summary>
        /// 刷新ListView项目
        /// </summary>
        /// <param name="listViewName">ListView名称</param>
        /// <param name="items">新的项目集合</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> RefreshListViewAsync(string listViewName, IEnumerable<ListViewItem> items, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            if (!_registeredControls.TryGetValue(listViewName, out var control) || !(control is ListView listView))
            {
                return UIUpdateResult.Failure($"未找到ListView控件: {listViewName}");
            }

            using (var transaction = _uiUpdateService.BeginTransaction($"RefreshListView_{listViewName}"))
            {
                var updates = new List<IUIUpdate>
                {
                    UIUpdateFactory.ClearCollection(listView, priority),
                    UIUpdateFactory.AddRangeToCollection(listView, items.Cast<object>(), priority)
                };

                var result = await _uiUpdateService.ExecuteInTransactionAsync(transaction, updates);
                return result.IsSuccess 
                    ? UIUpdateResult.Success($"成功刷新ListView {listViewName}")
                    : UIUpdateResult.Failure($"刷新ListView失败: {result.Message}");
            }
        }

        #endregion

        #region ComboBox专用操作

        /// <summary>
        /// 更新ComboBox数据源
        /// </summary>
        /// <param name="comboBoxName">ComboBox名称</param>
        /// <param name="dataSource">数据源</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> UpdateComboBoxDataSourceAsync(string comboBoxName, object dataSource, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            return await UpdateControlPropertyAsync(comboBoxName, "DataSource", dataSource, priority);
        }

        /// <summary>
        /// 设置ComboBox选中项
        /// </summary>
        /// <param name="comboBoxName">ComboBox名称</param>
        /// <param name="selectedItem">选中项</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> SetComboBoxSelectedItemAsync(string comboBoxName, object selectedItem, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            return await UpdateControlPropertyAsync(comboBoxName, "SelectedItem", selectedItem, priority);
        }

        /// <summary>
        /// 设置ComboBox选中索引
        /// </summary>
        /// <param name="comboBoxName">ComboBox名称</param>
        /// <param name="selectedIndex">选中索引</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> SetComboBoxSelectedIndexAsync(string comboBoxName, int selectedIndex, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            return await UpdateControlPropertyAsync(comboBoxName, "SelectedIndex", selectedIndex, priority);
        }

        #endregion

        #region 进度条和状态更新

        /// <summary>
        /// 更新进度条
        /// </summary>
        /// <param name="progressBarName">进度条名称</param>
        /// <param name="value">进度值</param>
        /// <param name="maximum">最大值（可选）</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> UpdateProgressBarAsync(string progressBarName, int value, int? maximum = null, UIUpdatePriority priority = UIUpdatePriority.High)
        {
            var updates = new Dictionary<string, object> { { "Value", value } };
            if (maximum.HasValue)
            {
                updates["Maximum"] = maximum.Value;
            }

            var updateOperations = UIUpdateFactory.UpdateProperties(_registeredControls[progressBarName], updates, priority);
            var batchResult = await _uiUpdateService.ExecuteBatchUpdateAsync(updateOperations);

            return batchResult.IsSuccess 
                ? UIUpdateResult.Success($"成功更新进度条 {progressBarName}")
                : UIUpdateResult.Failure($"更新进度条失败: {batchResult.Message}");
        }

        /// <summary>
        /// 更新状态标签
        /// </summary>
        /// <param name="statusLabelName">状态标签名称</param>
        /// <param name="status">状态文本</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> UpdateStatusLabelAsync(string statusLabelName, string status, UIUpdatePriority priority = UIUpdatePriority.High)
        {
            return await UpdateControlTextAsync(statusLabelName, status, priority);
        }

        #endregion

        #region 批量状态操作

        /// <summary>
        /// 批量设置控件启用状态
        /// </summary>
        /// <param name="controlNames">控件名称集合</param>
        /// <param name="enabled">是否启用</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>批量更新结果</returns>
        public async Task<UIBatchUpdateResult> SetControlsEnabledAsync(IEnumerable<string> controlNames, bool enabled, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            var controls = controlNames
                .Where(name => _registeredControls.ContainsKey(name))
                .Select(name => _registeredControls[name]);

            var updates = UIUpdateFactory.SetControlsEnabled(controls, enabled, priority);
            return await _uiUpdateService.ExecuteBatchUpdateAsync(updates);
        }

        /// <summary>
        /// 批量设置控件可见性
        /// </summary>
        /// <param name="controlNames">控件名称集合</param>
        /// <param name="visible">是否可见</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>批量更新结果</returns>
        public async Task<UIBatchUpdateResult> SetControlsVisibilityAsync(IEnumerable<string> controlNames, bool visible, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            var controls = controlNames
                .Where(name => _registeredControls.ContainsKey(name))
                .Select(name => _registeredControls[name]);

            var updates = UIUpdateFactory.SetControlsVisibility(controls, visible, priority);
            return await _uiUpdateService.ExecuteBatchUpdateAsync(updates);
        }

        /// <summary>
        /// 重置UI状态到默认值
        /// </summary>
        /// <param name="defaultStates">默认状态定义</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>批量更新结果</returns>
        public async Task<UIBatchUpdateResult> ResetUIToDefaultStateAsync(Dictionary<string, object> defaultStates, UIUpdatePriority priority = UIUpdatePriority.High)
        {
            var updates = new List<IUIUpdate>();

            foreach (var state in defaultStates)
            {
                var controlName = state.Key;
                var defaultValue = state.Value;

                if (_registeredControls.TryGetValue(controlName, out var control))
                {
                    // 假设默认状态是一个包含属性值的匿名对象
                    updates.AddRange(UIUpdateFactory.UpdateProperties(control, defaultValue, priority));
                }
            }

            return await _uiUpdateService.ExecuteBatchUpdateAsync(updates);
        }

        #endregion

        #region 自定义操作

        /// <summary>
        /// 执行自定义UI操作
        /// </summary>
        /// <param name="name">操作名称</param>
        /// <param name="action">操作Action</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> ExecuteCustomActionAsync(string name, Action action, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            var update = UIUpdateFactory.WrapAction(name, action, priority);
            return await _uiUpdateService.ExecuteUpdateAsync(update);
        }

        /// <summary>
        /// 执行自定义UI函数
        /// </summary>
        /// <typeparam name="T">返回值类型</typeparam>
        /// <param name="name">操作名称</param>
        /// <param name="func">操作Func</param>
        /// <param name="priority">更新优先级</param>
        /// <returns>更新结果</returns>
        public async Task<UIUpdateResult> ExecuteCustomFuncAsync<T>(string name, Func<T> func, UIUpdatePriority priority = UIUpdatePriority.Normal)
        {
            var update = UIUpdateFactory.WrapFunc(name, func, priority);
            return await _uiUpdateService.ExecuteUpdateAsync(update);
        }

        #endregion

        #region 事件处理

        /// <summary>
        /// 订阅UI更新服务事件
        /// </summary>
        private void SubscribeToUIUpdateServiceEvents()
        {
            _uiUpdateService.UpdateStarted += OnUIUpdateStarted;
            _uiUpdateService.UpdateCompleted += OnUIUpdateCompleted;
            _uiUpdateService.UpdateFailed += OnUIUpdateFailed;
            _uiUpdateService.StatusChanged += OnUIUpdateServiceStatusChanged;
        }

        /// <summary>
        /// 取消订阅UI更新服务事件
        /// </summary>
        private void UnsubscribeFromUIUpdateServiceEvents()
        {
            _uiUpdateService.UpdateStarted -= OnUIUpdateStarted;
            _uiUpdateService.UpdateCompleted -= OnUIUpdateCompleted;
            _uiUpdateService.UpdateFailed -= OnUIUpdateFailed;
            _uiUpdateService.StatusChanged -= OnUIUpdateServiceStatusChanged;
        }

        /// <summary>
        /// UI更新开始事件处理
        /// </summary>
        private void OnUIUpdateStarted(object sender, UIUpdateStartedEventArgs e)
        {
            if (LogManager.IsDebugEnabled)
            {
                LogManager.Debug($"[MainPluginUICoordinator] UI更新开始: {e.UpdateName} ({e.UpdateId})");
            }
        }

        /// <summary>
        /// UI更新完成事件处理
        /// </summary>
        private void OnUIUpdateCompleted(object sender, UIUpdateCompletedEventArgs e)
        {
            if (LogManager.IsDebugEnabled)
            {
                LogManager.Debug($"[MainPluginUICoordinator] UI更新完成: {e.UpdateName} ({e.UpdateId}) - {e.Result.Message}");
            }
        }

        /// <summary>
        /// UI更新失败事件处理
        /// </summary>
        private void OnUIUpdateFailed(object sender, UIUpdateFailedEventArgs e)
        {
            LogManager.Warning($"[MainPluginUICoordinator] UI更新失败: {e.UpdateName} ({e.UpdateId}) - {e.Exception?.Message}");
        }

        /// <summary>
        /// UI更新服务状态变化事件处理
        /// </summary>
        private void OnUIUpdateServiceStatusChanged(object sender, UIUpdateServiceStatusChangedEventArgs e)
        {
            LogManager.Info($"[MainPluginUICoordinator] UI更新服务状态变化: {e.PreviousStatus} -> {e.CurrentStatus}");
        }

        #endregion

        #region IDisposable实现

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            try
            {
                LogManager.Info("[MainPluginUICoordinator] 开始释放UI协调器");

                // 取消订阅事件
                UnsubscribeFromUIUpdateServiceEvents();

                // 清理注册的控件
                _registeredControls.Clear();

                // 释放UI更新服务
                if (_uiUpdateService is IDisposable disposableService)
                {
                    disposableService.Dispose();
                }

                _isDisposed = true;
                LogManager.Info("[MainPluginUICoordinator] UI协调器已释放");
            }
            catch (Exception ex)
            {
                LogManager.Error("[MainPluginUICoordinator] 释放UI协调器时发生异常", ex);
            }
        }

        #endregion
    }
}