using System;
using System.Collections.Specialized;
using Avalonia.Controls;
using Avalonia.Input;
using ClaudeDo.Ui.ViewModels.Islands;

namespace ClaudeDo.Ui.Views.Islands.Detail;

public partial class WorkConsole : UserControl
{
    private INotifyCollectionChanged? _log;

    public WorkConsole()
    {
        InitializeComponent();
        DataContextChanged += OnDataContextChanged;
    }

    private void OnDataContextChanged(object? sender, EventArgs e)
    {
        if (_log is not null)
            _log.CollectionChanged -= OnLogChanged;

        _log = (DataContext as DetailsIslandViewModel)?.Log;

        if (_log is not null)
            _log.CollectionChanged += OnLogChanged;
    }

    private void OnLogChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action != NotifyCollectionChangedAction.Add) return;
        EventHandler? handler = null;
        handler = (_, _) =>
        {
            LogScroll.LayoutUpdated -= handler;
            LogScroll.ScrollToEnd();
        };
        LogScroll.LayoutUpdated += handler;
    }

    private void OnReviewInputKeyDown(object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter || e.KeyModifiers.HasFlag(KeyModifiers.Shift))
            return;

        if (DataContext is DetailsIslandViewModel vm &&
            vm.RejectReviewCommand.CanExecute(null))
        {
            vm.RejectReviewCommand.Execute(null);
        }

        e.Handled = true;
    }
}
