using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using static GTPCorrgir.Opciones;
using static System.Net.WebRequestMethods;
using Brushes = System.Windows.Media.Brushes;
using Color = System.Windows.Media.Color;
using ComboBox = System.Windows.Controls.ComboBox;
using Cursors = System.Windows.Input.Cursors;
using FontFamily = System.Windows.Media.FontFamily;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using Timer = System.Windows.Forms.Timer;

namespace GTPCorrgir
{
    public partial class Chat : Window
    {
        gtpask AI_API;
        string respuestas;
        private Timer opacityTimer;
        private bool isMouseOver = false;
        private const double OPACITY_ACTIVE = 1.0;
        private const double OPACITY_INACTIVE = 0.2;
        private const int OPACITY_DELAY_MS = 3000; // 10 segundos

        public Chat(gtpask GTP)
        {
            InitializeComponent();
            InitializeOpacityTimer();
            PositionWindow();

            // Inicializar componentes de la UI
            AI_API = GTP;
            questionArea.Text = "";
            respuestas = "";

            this.Opacity = OPACITY_ACTIVE;

            InitializeModelSelector();
        }

        private void InitializeOpacityTimer()
        {
            opacityTimer = new Timer();
            opacityTimer.Interval = OPACITY_DELAY_MS;
            opacityTimer.Tick += (s, e) =>
            {
                if (!isMouseOver)
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        this.Opacity = OPACITY_INACTIVE;
                    });
                }
                opacityTimer.Stop();
            };
        }

        private void InitializeModelSelector()
        {
            foreach (KeyValuePair<LLM_a_Usar, string> kvp in Opciones.Instance.nombreLLM)
            {
                ComboBoxItem item = new ComboBoxItem();
                item.Content = kvp.Value;
                item.Tag = kvp.Key;
                modelSelector.Items.Add(item);

                if (kvp.Key == Opciones.Instance.LLM)
                {
                    modelSelector.SelectedItem = item;
                }
            }
        }

        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            var settingsWindow = new SettingsWindow
            {
                Owner = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            if (settingsWindow.ShowDialog() == true)
            {
                // Aplicar cambios de configuración
                ApplySettings();
            }
        }

        private void ApplySettings()
        {
            var settings = UserSettings.Instance;

            // Aplicar opacidad
            opacityTimer.Stop();
            opacityTimer.Interval = ((int)TimeSpan.FromMilliseconds(settings.Appearance.OpacityDelay).TotalMilliseconds);

            // Aplicar fuente
            questionArea.FontFamily = new FontFamily(settings.Appearance.FontFamily);
            questionArea.FontSize = settings.Appearance.FontSize;
            responseArea.FontFamily = new FontFamily(settings.Appearance.FontFamily);
            responseArea.FontSize = settings.Appearance.FontSize;

            // Aplicar tema
            if (settings.Appearance.Theme == "Dark")
            {
                // Aplicar tema oscuro
                this.Background = new SolidColorBrush(Color.FromArgb(200, 30, 30, 30));
                responseArea.Background = new SolidColorBrush(Color.FromArgb(255, 40, 40, 40));
                responseArea.Foreground = Brushes.White;
                questionArea.Background = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50));
                questionArea.Foreground = Brushes.White;
            }
            else
            {
                // Aplicar tema claro
                this.Background = new SolidColorBrush(Color.FromArgb(200, 240, 240, 240));
                responseArea.Background = Brushes.White;
                responseArea.Foreground = Brushes.Black;
                questionArea.Background = Brushes.White;
                questionArea.Foreground = Brushes.Black;
            }
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            ApplySettings(); // Aplicar configuración inicial
        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        private void Window_MouseEnter(object sender, MouseEventArgs e)
        {
            isMouseOver = true;
            opacityTimer.Stop();
            this.Opacity = OPACITY_ACTIVE;
        }

        private void Window_MouseLeave(object sender, MouseEventArgs e)
        {
            isMouseOver = false;
            opacityTimer.Start();
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }

        private void QuestionArea_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && !e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                SendButton_Click(this, new RoutedEventArgs());
                e.Handled = true;
            }
        }

        private async void SendButton_Click(object sender, RoutedEventArgs e)
        {
            AI_API.TextoACorregir = questionArea.Text;
            if (AI_API.TextoACorregir.Length > 3)
            {
                try
                {
                    sendButton.IsEnabled = false;
                    Mouse.OverrideCursor = Cursors.Wait;

                    await Task.Run(async () =>
                    {
                        try
                        {
                            await AI_API.CorregirTexto();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Error durante la corrección de texto: {ex.Message}");
                            throw;
                        }
                    });

                    if (AI_API.TextoCorregido != null)
                    {
                        System.Windows.Clipboard.SetText(AI_API.TextoCorregido);
                        AddMarkdownContent(AI_API.TextoCorregido + "\r\n");
                    }
                }
                catch (Exception ex)
                {
                    AddMarkdownContent($"Error: {ex.Message}\r\n");
                }
                finally
                {
                    Mouse.OverrideCursor = null;
                    sendButton.IsEnabled = true;
                }
            }
        }

        public void AddMarkdownContent(string markdownText)
        {
            var markdown = new Markdown.Xaml.Markdown();
            respuestas += markdownText + "\r\n";
            responseArea.Document = markdown.Transform(respuestas);
        }

        private void PositionWindow()
        {
            var cursorPosition = System.Windows.Forms.Cursor.Position;
            var screen = Screen.FromPoint(cursorPosition);
            this.Left = (screen.WorkingArea.Width - this.Width) / 2 + screen.WorkingArea.Left;
            this.Top = (screen.WorkingArea.Height - this.Height) / 2 + screen.WorkingArea.Top;
        }

        private void CambiarModelo(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox comboBox && comboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                Opciones.Instance.LLM = (LLM_a_Usar)selectedItem.Tag;
            }
        }

        private void clearButton_Click(object sender, RoutedEventArgs e)
        {
            respuestas = "";
            AddMarkdownContent("");
        }

        protected override void OnClosed(EventArgs e)
        {
            opacityTimer?.Dispose();
            base.OnClosed(e);
        }
    }
}