using System;
using System.Windows;
using System.Windows.Media;
using System.Linq;
using System.Windows.Controls;
using MessageBox = System.Windows.MessageBox;
using TextBox = System.Windows.Controls.TextBox;
using Button = System.Windows.Controls.Button;

namespace GTPCorrgir
{
    public partial class SettingsWindow : Window
    {
        private readonly UserSettings settings;
        private readonly ErrorLogger errorLogger;
        private readonly ChatHistory chatHistory;

        public SettingsWindow()
        {
            InitializeComponent();
            settings = UserSettings.Instance;
            errorLogger = new ErrorLogger();
            chatHistory = new ChatHistory();

            LoadSettings();
            InitializeFontControls();
        }

        private void InitializeFontControls()
        {
            // Cargar tamaños de fuente comunes
            FontSizeCombo.ItemsSource = new[] { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24 };
            FontSizeCombo.SelectedItem = settings.Appearance.FontSize;

            // Cargar fuentes del sistema
            var fontFamilies = Fonts.SystemFontFamilies
                .OrderBy(f => f.Source)
                .Select(f => f.Source);
            FontFamilyCombo.ItemsSource = fontFamilies;
            FontFamilyCombo.SelectedItem = settings.Appearance.FontFamily;
        }

        private void LoadSettings()
        {
            // Tema
            (settings.Appearance.Theme == "Light" ? LightTheme : DarkTheme).IsChecked = true;

            // Opacidad
            OpacityDelaySlider.Value = settings.Appearance.OpacityDelay / 1000.0;

            // Comportamiento
            AutoSaveCheckbox.IsChecked = settings.Behavior.AutoSaveHistory;
            ShowNotificationsCheckbox.IsChecked = settings.Behavior.ShowNotifications;
            AutoCopyCheckbox.IsChecked = settings.Behavior.AutoCopyToClipboard;
            NotificationDurationSlider.Value = settings.Behavior.NotificationDuration / 1000.0;
        }

        private async void ViewErrorLogs_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string summary = await errorLogger.GetErrorSummaryAsync();
                ShowScrollableDialog("Registros de Error", summary);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error al cargar los registros: {ex.Message}",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ShowScrollableDialog(string title, string content)
        {
            var dialog = new Window
            {
                Title = title,
                Width = 600,
                Height = 400,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this,
                ResizeMode = ResizeMode.CanResize,
                ShowInTaskbar = false
            };

            var textBox = new TextBox
            {
                Text = content,
                IsReadOnly = true,
                TextWrapping = TextWrapping.Wrap,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                Margin = new Thickness(10),
                AcceptsReturn = true
            };

            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            var closeButton = new Button
            {
                Content = "Cerrar",
                Width = 80,
                Height = 25,
                Margin = new Thickness(10),
                HorizontalAlignment = System.Windows.HorizontalAlignment.Right
            };
            closeButton.Click += (s, e) => dialog.Close();

            Grid.SetRow(textBox, 0);
            Grid.SetRow(closeButton, 1);

            grid.Children.Add(textBox);
            grid.Children.Add(closeButton);

            dialog.Content = grid;
            dialog.ShowDialog();
        }

        private async void ClearHistory_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(
                "¿Está seguro de que desea borrar todo el historial de chat?\nEsta acción no se puede deshacer.",
                "Confirmar borrado",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning
            );

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    // Aquí implementarías la lógica para borrar el historial
                    // Por ejemplo: await chatHistory.ClearAllAsync();

                    MessageBox.Show(
                        "El historial ha sido borrado correctamente.",
                        "Éxito",
                        MessageBoxButton.OK,
                        MessageBoxImage.Information
                    );
                }
                catch (Exception ex)
                {
                    await errorLogger.LogErrorAsync(ex, "Error al borrar historial");
                    MessageBox.Show(
                        $"Error al borrar el historial: {ex.Message}",
                        "Error",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error
                    );
                }
            }
        }

        private void ResetSettings_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(
                "¿Está seguro de que desea restablecer toda la configuración a sus valores predeterminados?",
                "Confirmar restablecimiento",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning
            );

            if (result == MessageBoxResult.Yes)
            {
                settings.ResetToDefaults();
                LoadSettings();
                MessageBox.Show(
                    "La configuración ha sido restablecida correctamente.",
                    "Éxito",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information
                );
            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Guardar tema
                settings.Appearance.Theme = LightTheme.IsChecked == true ? "Light" : "Dark";

                // Guardar fuente
                if (FontSizeCombo.SelectedItem != null)
                    settings.Appearance.FontSize = (int)FontSizeCombo.SelectedItem;

                if (FontFamilyCombo.SelectedItem != null)
                    settings.Appearance.FontFamily = FontFamilyCombo.SelectedItem.ToString();

                // Guardar opacidad
                settings.Appearance.OpacityDelay = (int)(OpacityDelaySlider.Value * 1000);

                // Guardar comportamiento
                settings.Behavior.AutoSaveHistory = AutoSaveCheckbox.IsChecked ?? false;
                settings.Behavior.ShowNotifications = ShowNotificationsCheckbox.IsChecked ?? true;
                settings.Behavior.AutoCopyToClipboard = AutoCopyCheckbox.IsChecked ?? true;
                settings.Behavior.NotificationDuration = (int)(NotificationDurationSlider.Value * 1000);

                settings.Save();
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    $"Error al guardar la configuración: {ex.Message}",
                    "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error
                );
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }
}