using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Data;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MessageBox = System.Windows.MessageBox;

namespace GTPCorrgir
{
    public class NullToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value != null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public partial class ContextMenuWindow : Window
    {
        public class MenuOption
        {
            public string DisplayName { get; set; }
            public object Value { get; set; }
        }

        private readonly List<MenuOption> modeOptions;
        private readonly List<MenuOption> llmOptions;
        private bool optionsSelected = false;

        public ContextMenuWindow()
        {
            // Initialize lists in constructor
            modeOptions = new List<MenuOption>
            {
                new MenuOption { DisplayName = "Corregir texto", Value = Opciones.modoDeUso.Corregir },
                new MenuOption { DisplayName = "Revisar ortografía", Value = Opciones.modoDeUso.Ortografia },
                new MenuOption { DisplayName = "Chat", Value = Opciones.modoDeUso.Chat },
                new MenuOption { DisplayName = "Pregunta-Respuesta", Value = Opciones.modoDeUso.PreguntaRespuesta },
                new MenuOption { DisplayName = "Traducir a inglés", Value = Opciones.modoDeUso.Traducir_a_Ingles },
                new MenuOption { DisplayName = "Traducir a italiano", Value = Opciones.modoDeUso.Traducir_a_Italiano },
                new MenuOption { DisplayName = "Traducir a español", Value = Opciones.modoDeUso.Traducir_a_Espanol },
                new MenuOption { DisplayName = "Traducir a portugués", Value = Opciones.modoDeUso.Traducir_a_Portugues },
                new MenuOption { DisplayName = "OCR a texto", Value = Opciones.modoDeUso.OCRaTexto }
            };

            llmOptions = new List<MenuOption>
            {
                new MenuOption { DisplayName = "OpenAI", Value = Opciones.LLM_a_Usar.OpenAI },
                new MenuOption { DisplayName = "Ollama", Value = Opciones.LLM_a_Usar.Ollama },
                new MenuOption { DisplayName = "Groq", Value = Opciones.LLM_a_Usar.Groq },
                new MenuOption { DisplayName = "Grok", Value = Opciones.LLM_a_Usar.Grok }
            };

            InitializeComponent();
            InitializeControls();
            LoadSavedSelections();

            // Posicionar la ventana después de que se haya cargado completamente
            this.Loaded += (s, e) => PositionWindowAtCursor();
        }

        private void InitializeControls()
        {
            ModeListBox.ItemsSource = modeOptions;
            LLMListBox.ItemsSource = llmOptions;
        }

        private void LoadSavedSelections()
        {
            var savedSettings = MenuSettings.Instance;

            var savedMode = modeOptions.FirstOrDefault(x =>
                (Opciones.modoDeUso)x.Value == savedSettings.Options.LastUsedMode);
            var savedLLM = llmOptions.FirstOrDefault(x =>
                (Opciones.LLM_a_Usar)x.Value == savedSettings.Options.LastUsedLLM);

            if (savedMode != null)
                ModeListBox.SelectedItem = savedMode;

            if (savedLLM != null)
                LLMListBox.SelectedItem = savedLLM;
        }

        private void PositionWindowAtCursor()
        {
            var cursorPosition = System.Windows.Forms.Cursor.Position;
            var screen = Screen.FromPoint(cursorPosition);

            // Calculate position ensuring the window stays within screen bounds
            double left = cursorPosition.X;
            double top = cursorPosition.Y;

            // Get the window size (waiting for it to be rendered)
            this.UpdateLayout();
            double windowWidth = this.ActualWidth;
            double windowHeight = this.ActualHeight;

            // Adjust position if window would go off screen
            if (left + windowWidth > screen.WorkingArea.Right)
            {
                left = screen.WorkingArea.Right - windowWidth;
            }

            if (top + windowHeight > screen.WorkingArea.Bottom)
            {
                top = screen.WorkingArea.Bottom - windowHeight;
            }

            // Ensure window doesn't go off the left or top of the screen
            left = Math.Max(screen.WorkingArea.Left, left);
            top = Math.Max(screen.WorkingArea.Top, top);

            this.Left = left;
            this.Top = top;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

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

        private void Window_Deactivated(object sender, EventArgs e)
        {
            // Elimina este evento o modifícalo para que no cierre automáticamente
            // if (!optionsSelected)
            // {
            //     this.DialogResult = false;
            //     this.Close();
            // }
        }

        private void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            if (ModeListBox.SelectedItem is MenuOption selectedMode &&
                LLMListBox.SelectedItem is MenuOption selectedLLM)
            {
                UpdateOptionsAndClose(selectedMode, selectedLLM);
            }
        }
        private void UpdateOptionsAndClose(MenuOption selectedMode, MenuOption selectedLLM)
        {
            optionsSelected = true;

            var modeValue = (Opciones.modoDeUso)selectedMode.Value;
            var llmValue = (Opciones.LLM_a_Usar)selectedLLM.Value;

            Opciones.Instance.modo = modeValue;
            Opciones.Instance.LLM = llmValue;

            MenuSettings.Instance.UpdateLastUsedOptions(modeValue, llmValue);

            // Eliminar DialogResult
            this.Close();
        }
    }
}