using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using MarkdownEditor.ViewModels;

namespace MarkdownEditor.Views;

/// <summary>
/// VSCode-style find panel overlay for searching text in both raw and pretty views.
/// </summary>
public partial class FindPanel : UserControl
{
    /// <summary>
    /// Initializes a new instance of the <see cref="FindPanel"/> class.
    /// </summary>
    public FindPanel()
    {
        InitializeComponent();
    }

    /// <inheritdoc/>
    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);
        // Focus the search text box when the panel is shown
        SearchTextBox?.Focus();
        SearchTextBox?.SelectAll();
    }

    private void OnSearchTextBoxKeyDown(object? sender, KeyEventArgs e)
    {
        if (DataContext is not MarkdownTabViewModel viewModel)
            return;

        switch (e.Key)
        {
            case Key.Enter:
                if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
                {
                    viewModel.FindPreviousCommand.Execute(null);
                }
                else
                {
                    viewModel.FindNextCommand.Execute(null);
                }
                e.Handled = true;
                break;

            case Key.Escape:
                viewModel.CloseFindPanelCommand.Execute(null);
                e.Handled = true;
                break;
        }
    }
}
