using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using NavisworksTransport.Core.Config;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 配置编辑器对话框
    /// </summary>
    public partial class ConfigEditorDialog : Window
    {
        private string _originalContent;
        private bool _isModified;

        public ConfigEditorDialog()
        {
            InitializeComponent();
            LoadConfigContent();
            UpdateStatus();
        }

        /// <summary>
        /// 加载配置文件内容
        /// </summary>
        private void LoadConfigContent()
        {
            try
            {
                string configPath = ConfigManager.ConfigFilePath;

                // 如果配置文件不存在，创建默认配置
                if (!File.Exists(configPath))
                {
                    ConfigManager.Instance.Current.GetType(); // 触发单例初始化
                }

                // 读取配置文件
                if (File.Exists(configPath))
                {
                    _originalContent = File.ReadAllText(configPath, System.Text.Encoding.UTF8);
                    ConfigContentTextBox.Text = _originalContent;
                    ConfigFilePathLabel.Content = Path.GetFileName(configPath);
                    StatusLabel.Content = "配置已加载";
                    StatusLabel.Foreground = System.Windows.Media.Brushes.Green;
                }
                else
                {
                    StatusLabel.Content = "配置文件不存在";
                    StatusLabel.Foreground = System.Windows.Media.Brushes.Red;
                }

                _isModified = false;
                ModifiedLabel.Content = "";
            }
            catch (Exception ex)
            {
                LogManager.Error($"加载配置文件失败: {ex.Message}");
                MessageBox.Show($"加载配置文件失败:\n{ex.Message}",
                    "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 更新状态信息
        /// </summary>
        private void UpdateStatus()
        {
            try
            {
                string configPath = ConfigManager.ConfigFilePath;

                if (File.Exists(configPath))
                {
                    var fileInfo = new FileInfo(configPath);
                    FileSizeLabel.Content = $"大小: {fileInfo.Length / 1024.0:F2} KB";
                }

                int lineCount = ConfigContentTextBox.LineCount;
                LineCountLabel.Content = $"行数: {lineCount}";
            }
            catch (Exception ex)
            {
                LogManager.Error($"更新状态信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private bool SaveConfig()
        {
            try
            {
                string configPath = ConfigManager.ConfigFilePath;
                string content = ConfigContentTextBox.Text;

                // 验证 TOML 格式
                try
                {
                    Tomlyn.Toml.ToModel(content);
                }
                catch (Exception tomlEx)
                {
                    MessageBox.Show($"TOML 格式错误:\n{tomlEx.Message}\n\n请检查配置文件语法。",
                        "格式错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                // 确保目录存在
                Directory.CreateDirectory(ConfigManager.ConfigDirectory);

                // 保存文件
                File.WriteAllText(configPath, content, System.Text.Encoding.UTF8);

                // 重新加载配置
                ConfigManager.Instance.Reload();

                _originalContent = content;
                _isModified = false;
                ModifiedLabel.Content = "";

                StatusLabel.Content = "配置已保存";
                StatusLabel.Foreground = System.Windows.Media.Brushes.Green;

                UpdateStatus();

                LogManager.Info("配置文件已保存");
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Error($"保存配置失败: {ex.Message}");
                MessageBox.Show($"保存配置失败:\n{ex.Message}",
                    "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }

        // 事件处理器

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            SaveConfig();
        }

        private void ReloadButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isModified)
            {
                var result = MessageBox.Show(
                    "当前有未保存的修改，重新加载将丢失这些修改。\n\n确定要继续吗？",
                    "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result != MessageBoxResult.Yes)
                    return;
            }

            LoadConfigContent();
            StatusLabel.Content = "配置已重新加载";
            StatusLabel.Foreground = System.Windows.Media.Brushes.Green;
        }

        private void ResetToDefaultButton_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(
                "确定要恢复为默认配置吗？\n\n当前配置将被覆盖，此操作无法撤销。",
                "确认", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    ConfigManager.Instance.RestoreToDefaults();
                    LoadConfigContent();
                    StatusLabel.Content = "已恢复默认配置";
                    StatusLabel.Foreground = System.Windows.Media.Brushes.Green;
                    LogManager.Info("配置已恢复为默认值");
                }
                catch (Exception ex)
                {
                    LogManager.Error($"恢复默认配置失败: {ex.Message}");
                    MessageBox.Show($"恢复默认配置失败:\n{ex.Message}",
                        "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void OpenConfigFolderButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string configDir = ConfigManager.ConfigDirectory;

                if (!Directory.Exists(configDir))
                {
                    Directory.CreateDirectory(configDir);
                }

                Process.Start("explorer.exe", configDir);
                LogManager.Info($"打开配置文件夹: {configDir}");
            }
            catch (Exception ex)
            {
                LogManager.Error($"打开配置文件夹失败: {ex.Message}");
                MessageBox.Show($"打开配置文件夹失败:\n{ex.Message}",
                    "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
            SaveConfig();
        }

        private void OkButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isModified)
            {
                if (SaveConfig())
                {
                    DialogResult = true;
                    Close();
                }
            }
            else
            {
                DialogResult = true;
                Close();
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isModified)
            {
                var result = MessageBox.Show(
                    "有未保存的修改，确定要关闭吗？",
                    "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result != MessageBoxResult.Yes)
                    return;
            }

            DialogResult = false;
            Close();
        }

        private void ConfigContentTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_originalContent != null)
            {
                _isModified = ConfigContentTextBox.Text != _originalContent;

                if (_isModified)
                {
                    ModifiedLabel.Content = "● 已修改";
                }
                else
                {
                    ModifiedLabel.Content = "";
                }

                UpdateStatus();
            }
        }
    }
}
