using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using AxCopilot.SDK;
using AxCopilot.Services;

namespace AxCopilot.Handlers;

public class NoteHandler : IActionHandler
{
	private static readonly string NotesFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AxCopilot", "notes.txt");

	public string? Prefix => "note";

	public PluginMetadata Metadata => new PluginMetadata("Note", "빠른 메모 — note 뒤에 내용 입력", "1.0", "AX");

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		string text = query.Trim();
		if (string.IsNullOrWhiteSpace(text))
		{
			List<NoteEntry> list = ReadNotes();
			if (!list.Any())
			{
				return Task.FromResult((IEnumerable<LauncherItem>)new _003C_003Ez__ReadOnlySingleElementList<LauncherItem>(new LauncherItem("메모가 없습니다", "note 뒤에 내용을 입력하면 저장됩니다", null, null, null, "\ue70b")));
			}
			List<LauncherItem> list2 = (from n in list.Take(10)
				select new LauncherItem((n.Content.Length > 60) ? (n.Content.Substring(0, 57) + "…") : n.Content, $"{n.SavedAt:yyyy-MM-dd HH:mm}  ·  Enter 복사 · Delete 삭제", null, n.Content, null, "\ue70b")).ToList();
			list2.Add(new LauncherItem("전체 메모 삭제", $"총 {list.Count}개 메모 모두 삭제  ·  Enter로 실행", null, "__CLEAR__", null, "\ue74d"));
			return Task.FromResult((IEnumerable<LauncherItem>)list2);
		}
		if (text.Equals("clear", StringComparison.OrdinalIgnoreCase))
		{
			int count = ReadNotes().Count;
			return Task.FromResult((IEnumerable<LauncherItem>)new _003C_003Ez__ReadOnlySingleElementList<LauncherItem>(new LauncherItem($"전체 메모 삭제 ({count}개)", "모든 메모를 삭제합니다  ·  Enter로 실행", null, "__CLEAR__", null, "\ue74d")));
		}
		return Task.FromResult((IEnumerable<LauncherItem>)new _003C_003Ez__ReadOnlySingleElementList<LauncherItem>(new LauncherItem("메모 저장: " + ((text.Length > 60) ? (text.Substring(0, 57) + "…") : text), $"{DateTime.Now:yyyy-MM-dd HH:mm}  ·  Enter로 저장", null, ("__SAVE__", text), null, "\ue70b")));
	}

	public Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		object data = item.Data;
		object obj = data;
		if (!(obj is (string, string) tuple))
		{
			if (obj is string text)
			{
				if (text == "__CLEAR__")
				{
					ClearNotes();
				}
				else
				{
					string text2 = text;
					try
					{
						Clipboard.SetText(text2);
					}
					catch
					{
					}
				}
			}
		}
		else if (tuple.Item1 == "__SAVE__")
		{
			SaveNote(tuple.Item2);
			NotificationService.Notify("AX Copilot", "메모 저장됨: " + ((tuple.Item2.Length > 30) ? (tuple.Item2.Substring(0, 27) + "…") : tuple.Item2));
		}
		return Task.CompletedTask;
	}

	private static void SaveNote(string content)
	{
		try
		{
			Directory.CreateDirectory(Path.GetDirectoryName(NotesFile));
			string contents = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {content}{Environment.NewLine}";
			File.AppendAllText(NotesFile, contents, Encoding.UTF8);
		}
		catch (Exception ex)
		{
			LogService.Warn("메모 저장 실패: " + ex.Message);
		}
	}

	private static List<NoteEntry> ReadNotes()
	{
		List<NoteEntry> list = new List<NoteEntry>();
		if (!File.Exists(NotesFile))
		{
			return list;
		}
		try
		{
			string[] source = File.ReadAllLines(NotesFile, Encoding.UTF8);
			foreach (string item in source.Reverse())
			{
				if (!string.IsNullOrWhiteSpace(item))
				{
					if (item.StartsWith('[') && item.Length > 21 && item[20] == ']' && DateTime.TryParse(item.Substring(1, 19), out var result))
					{
						DateTime savedAt = result;
						string text = item;
						list.Add(new NoteEntry(savedAt, text.Substring(22, text.Length - 22).Trim()));
					}
					else
					{
						list.Add(new NoteEntry(DateTime.MinValue, item.Trim()));
					}
				}
			}
		}
		catch (Exception ex)
		{
			LogService.Warn("메모 읽기 실패: " + ex.Message);
		}
		return list;
	}

	private static void ClearNotes()
	{
		try
		{
			if (File.Exists(NotesFile))
			{
				File.Delete(NotesFile);
			}
		}
		catch (Exception ex)
		{
			LogService.Warn("메모 삭제 실패: " + ex.Message);
		}
	}

	public static bool DeleteNote(string content)
	{
		try
		{
			if (!File.Exists(NotesFile))
			{
				return false;
			}
			List<string> list = File.ReadAllLines(NotesFile, Encoding.UTF8).ToList();
			for (int num = list.Count - 1; num >= 0; num--)
			{
				string text = list[num];
				if (!string.IsNullOrWhiteSpace(text))
				{
					string text3;
					if (text.StartsWith('[') && text.Length > 21 && text[20] == ']')
					{
						string text2 = text;
						text3 = text2.Substring(22, text2.Length - 22).Trim();
					}
					else
					{
						text3 = text.Trim();
					}
					if (text3 == content)
					{
						list.RemoveAt(num);
						File.WriteAllLines(NotesFile, list, Encoding.UTF8);
						return true;
					}
				}
			}
		}
		catch (Exception ex)
		{
			LogService.Warn("메모 개별 삭제 실패: " + ex.Message);
		}
		return false;
	}
}
