using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using ClaudeDo.Ui.ViewModels.Islands;

namespace ClaudeDo.Ui.Views.Islands.Detail;

public partial class DescriptionStepsCard : UserControl
{
    public DescriptionStepsCard()
    {
        InitializeComponent();
    }

    private async void OnCopyClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not DetailsIslandViewModel vm) return;
        var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
        if (clipboard is null) return;
        await clipboard.SetTextAsync(vm.ComposedPreview);
    }

    private void OnSubtaskTitleTapped(object? sender, TappedEventArgs e)
    {
        if (sender is TextBlock { DataContext: SubtaskRowViewModel row })
            row.IsEditing = true;
    }

    private void OnSubtaskEditLostFocus(object? sender, RoutedEventArgs e)
    {
        if (sender is TextBox { DataContext: SubtaskRowViewModel row }
            && DataContext is DetailsIslandViewModel vm
            && vm.CommitSubtaskEditCommand.CanExecute(row))
            vm.CommitSubtaskEditCommand.Execute(row);
    }

    private async void OnAddFileClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not DetailsIslandViewModel vm) return;
        var topLevel = TopLevel.GetTopLevel(this);
        if (topLevel is null) return;

        var picked = await topLevel.StorageProvider.OpenFilePickerAsync(
            new FilePickerOpenOptions { AllowMultiple = true });

        if (picked.Count == 0) return;

        var files = new List<(string FileName, System.IO.Stream Content)>();
        foreach (var item in picked)
        {
            var stream = await item.OpenReadAsync();
            files.Add((item.Name, stream));
        }

        try
        {
            await vm.AddFilesAsync(files);
        }
        finally
        {
            foreach (var (_, s) in files) await s.DisposeAsync();
        }
    }
}
