using Avalonia.Controls;
using Avalonia.Interactivity;
using ClaudeDo.Ui.ViewModels.Islands;
using ClaudeDo.Ui.ViewModels.Modals;
using ClaudeDo.Ui.Views.Modals;

namespace ClaudeDo.Ui.Views.Islands;

public partial class ListsIslandView : UserControl
{
    public ListsIslandView()
    {
        InitializeComponent();
        DataContextChanged += (_, _) =>
        {
            if (DataContext is ListsIslandViewModel vm)
            {
                vm.FocusSearchRequested += (_, _) => SearchBox.Focus();
                vm.ShowSettingsModal = ShowSettingsAsync;
                vm.ShowListSettingsModal = async modal =>
                {
                    var window = new ListSettingsModalView { DataContext = modal };
                    modal.CloseAction = () => window.Close();
                    var top = TopLevel.GetTopLevel(this) as Window;
                    if (top is null) window.Show();
                    else await window.ShowDialog(top);
                };
            }
        };
    }

    private void OnItemTapped(object? sender, RoutedEventArgs e)
    {
        if (sender is Border { DataContext: ListNavItemViewModel item }
            && DataContext is ListsIslandViewModel vm)
            vm.SelectCommand.Execute(item);
    }

    private async System.Threading.Tasks.Task ShowSettingsAsync(SettingsModalViewModel settingsVm)
    {
        var owner = TopLevel.GetTopLevel(this) as Window;
        if (owner == null) return;
        var modal = new SettingsModalView { DataContext = settingsVm };
        await modal.ShowDialog(owner);
    }
}
