using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;

namespace AxCopilot.Views;

public class TextActionPopup : Window, IComponentConnector
{
	private struct POINT
	{
		public int X;

		public int Y;
	}

	public enum ActionResult
	{
		None,
		OpenLauncher,
		Translate,
		Summarize,
		GrammarFix,
		Explain,
		Rewrite
	}

	private int _selectedIndex;

	private readonly List<(ActionResult Action, string Icon, string Label)> _items;

	private static readonly (string Key, ActionResult Action, string Icon, string Label)[] AllCommands = new(string, ActionResult, string, string)[5]
	{
		("translate", ActionResult.Translate, "\ue774", "번역"),
		("summarize", ActionResult.Summarize, "\ue8d2", "요약"),
		("grammar", ActionResult.GrammarFix, "\ue8ac", "문법 교정"),
		("explain", ActionResult.Explain, "\ue946", "설명"),
		("rewrite", ActionResult.Rewrite, "\ue70f", "다시 쓰기")
	};

	internal TextBlock PreviewText;

	internal StackPanel MenuItems;

	private bool _contentLoaded;

	public ActionResult SelectedAction { get; private set; } = ActionResult.None;

	public string SelectedText { get; private set; } = "";

	public static IReadOnlyList<(string Key, string Label)> AvailableCommands => AllCommands.Select(((string Key, ActionResult Action, string Icon, string Label) c) => (Key: c.Key, Label: c.Label)).ToList();

	[DllImport("user32.dll")]
	private static extern bool GetCursorPos(out POINT lpPoint);

	public TextActionPopup(string selectedText, List<string>? enabledCommands = null)
	{
		InitializeComponent();
		SelectedText = selectedText;
		string text = selectedText.Replace("\r\n", " ").Replace("\n", " ");
		PreviewText.Text = ((text.Length > 60) ? (text.Substring(0, 57) + "…") : text);
		List<string> source = enabledCommands ?? AllCommands.Select(((string Key, ActionResult Action, string Icon, string Label) c) => c.Key).ToList();
		_items = new List<(ActionResult, string, string)> { (ActionResult.OpenLauncher, "\ue8a7", "AX Commander 열기") };
		(string, ActionResult, string, string)[] allCommands = AllCommands;
		for (int num = 0; num < allCommands.Length; num++)
		{
			(string, ActionResult, string, string) tuple = allCommands[num];
			if (source.Contains<string>(tuple.Item1, StringComparer.OrdinalIgnoreCase))
			{
				_items.Add((tuple.Item2, tuple.Item3, tuple.Item4));
			}
		}
		BuildMenuItems();
		PositionAtCursor();
		base.Loaded += delegate
		{
			Focus();
			UpdateSelection();
		};
	}

	private void BuildMenuItems()
	{
		Brush foreground = (TryFindResource("PrimaryText") as Brush) ?? Brushes.White;
		Brush foreground2 = (TryFindResource("AccentColor") as Brush) ?? Brushes.CornflowerBlue;
		for (int i = 0; i < _items.Count; i++)
		{
			(ActionResult, string, string) tuple = _items[i];
			ActionResult action = tuple.Item1;
			string item = tuple.Item2;
			string item2 = tuple.Item3;
			int num = i;
			StackPanel stackPanel = new StackPanel
			{
				Orientation = Orientation.Horizontal
			};
			stackPanel.Children.Add(new TextBlock
			{
				Text = item,
				FontFamily = new FontFamily("Segoe MDL2 Assets"),
				FontSize = 14.0,
				Foreground = foreground2,
				VerticalAlignment = VerticalAlignment.Center,
				Margin = new Thickness(0.0, 0.0, 10.0, 0.0),
				Width = 20.0,
				TextAlignment = TextAlignment.Center
			});
			stackPanel.Children.Add(new TextBlock
			{
				Text = item2,
				FontSize = 13.0,
				Foreground = foreground,
				VerticalAlignment = VerticalAlignment.Center
			});
			Border border = new Border
			{
				Child = stackPanel,
				CornerRadius = new CornerRadius(8.0),
				Padding = new Thickness(10.0, 8.0, 14.0, 8.0),
				Margin = new Thickness(0.0, 1.0, 0.0, 1.0),
				Background = Brushes.Transparent,
				Cursor = Cursors.Hand,
				Tag = num
			};
			border.MouseEnter += delegate(object s, MouseEventArgs _)
			{
				if (s is Border { Tag: var tag } && tag is int selectedIndex)
				{
					_selectedIndex = selectedIndex;
					UpdateSelection();
				}
			};
			border.MouseLeftButtonUp += delegate
			{
				SelectedAction = action;
				Close();
			};
			MenuItems.Children.Add(border);
		}
	}

	private void UpdateSelection()
	{
		Brush brush = (TryFindResource("ItemHoverBackground") as Brush) ?? new SolidColorBrush(Color.FromArgb(24, byte.MaxValue, byte.MaxValue, byte.MaxValue));
		Brush brush2 = (TryFindResource("ItemSelectedBackground") as Brush) ?? new SolidColorBrush(Color.FromArgb(68, 75, 94, 252));
		for (int i = 0; i < MenuItems.Children.Count; i++)
		{
			if (MenuItems.Children[i] is Border border)
			{
				border.Background = ((i == _selectedIndex) ? brush2 : Brushes.Transparent);
			}
		}
	}

	private void PositionAtCursor()
	{
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		GetCursorPos(out var lpPoint);
		PresentationSource presentationSource = PresentationSource.FromVisual(this);
		double num = 1.0;
		double num2 = 1.0;
		if (presentationSource?.CompositionTarget != null)
		{
			Matrix transformFromDevice = presentationSource.CompositionTarget.TransformFromDevice;
			num = ((Matrix)(ref transformFromDevice)).M11;
			transformFromDevice = presentationSource.CompositionTarget.TransformFromDevice;
			num2 = ((Matrix)(ref transformFromDevice)).M22;
		}
		base.Left = (double)lpPoint.X * num;
		base.Top = (double)lpPoint.Y * num2 + 10.0;
		Rect workArea = SystemParameters.WorkArea;
		if (base.Left + 280.0 > ((Rect)(ref workArea)).Right)
		{
			base.Left = ((Rect)(ref workArea)).Right - 280.0;
		}
		if (base.Top + 300.0 > ((Rect)(ref workArea)).Bottom)
		{
			base.Top = (double)lpPoint.Y * num2 - 300.0;
		}
		if (base.Left < ((Rect)(ref workArea)).Left)
		{
			base.Left = ((Rect)(ref workArea)).Left;
		}
		if (base.Top < ((Rect)(ref workArea)).Top)
		{
			base.Top = ((Rect)(ref workArea)).Top;
		}
	}

	private void Window_KeyDown(object sender, KeyEventArgs e)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Invalid comparison between Unknown and I4
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Invalid comparison between Unknown and I4
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Invalid comparison between Unknown and I4
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Invalid comparison between Unknown and I4
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Invalid comparison between Unknown and I4
		Key key = e.Key;
		Key val = key;
		if ((int)val <= 13)
		{
			if ((int)val != 6)
			{
				if ((int)val == 13)
				{
					SelectedAction = ActionResult.None;
					Close();
					e.Handled = true;
				}
			}
			else
			{
				SelectedAction = _items[_selectedIndex].Action;
				Close();
				e.Handled = true;
			}
		}
		else if ((int)val != 24)
		{
			if ((int)val == 26)
			{
				_selectedIndex = (_selectedIndex + 1) % _items.Count;
				UpdateSelection();
				e.Handled = true;
			}
		}
		else
		{
			_selectedIndex = (_selectedIndex - 1 + _items.Count) % _items.Count;
			UpdateSelection();
			e.Handled = true;
		}
	}

	private void Window_Deactivated(object? sender, EventArgs e)
	{
		if (base.IsVisible)
		{
			Close();
		}
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "10.0.5.0")]
	public void InitializeComponent()
	{
		if (!_contentLoaded)
		{
			_contentLoaded = true;
			Uri resourceLocator = new Uri("/AxCopilot;component/views/textactionpopup.xaml", UriKind.Relative);
			Application.LoadComponent(this, resourceLocator);
		}
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "10.0.5.0")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	void IComponentConnector.Connect(int connectionId, object target)
	{
		switch (connectionId)
		{
		case 1:
			((TextActionPopup)target).Deactivated += Window_Deactivated;
			((TextActionPopup)target).KeyDown += Window_KeyDown;
			break;
		case 2:
			PreviewText = (TextBlock)target;
			break;
		case 3:
			MenuItems = (StackPanel)target;
			break;
		default:
			_contentLoaded = true;
			break;
		}
	}
}
