using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Markup.Xaml;
using System.Windows.Input;

namespace InABox.Avalonia.Components;

public partial class SearchBar : UserControl
{
    public static readonly StyledProperty<string> PlaceholderTextProperty =
        AvaloniaProperty.Register<SearchBar, string>(nameof(PlaceholderText), "Search...");

    public string PlaceholderText
    {
        get => GetValue(PlaceholderTextProperty);
        set => SetValue(PlaceholderTextProperty, value);
    }

    public static readonly StyledProperty<ICommand?> CommandProperty =
        AvaloniaProperty.Register<SearchBar, ICommand?>(nameof(Command), null);
   
    public ICommand? Command
    {
        get => GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public static readonly StyledProperty<string> TextProperty =
        AvaloniaProperty.Register<SearchBar, string>(nameof(Text), "", defaultBindingMode: BindingMode.TwoWay);

    public string Text
    {
        get => GetValue(TextProperty);
        set => SetValue(TextProperty, value);
    }

    public static readonly StyledProperty<bool> SearchOnChangedProperty =
        AvaloniaProperty.Register<SearchBar, bool>(nameof(SearchOnChanged), true);

    public bool SearchOnChanged
    {
        get => GetValue(SearchOnChangedProperty);
        set => SetValue(SearchOnChangedProperty, value);
    }

    public SearchBar()
    {
        InitializeComponent();
    }

    private void TextBox_TextChanged(object? sender, TextChangedEventArgs e)
    {
        if (SearchOnChanged && Command is not null && Command.CanExecute(null))
        {
            Command.Execute(null);
        }
    }
}