using System.Collections;
using System.Collections.Specialized;
using Avalonia;
using Avalonia.Controls;

namespace ClaudeDo.Ui.Views.Islands;

public partial class SessionTerminalView : UserControl
{
    public static readonly StyledProperty<IEnumerable?> EntriesProperty =
        AvaloniaProperty.Register<SessionTerminalView, IEnumerable?>(nameof(Entries));
    public static readonly StyledProperty<string?> LabelProperty =
        AvaloniaProperty.Register<SessionTerminalView, string?>(nameof(Label));
    public static readonly StyledProperty<bool> IsRunningProperty =
        AvaloniaProperty.Register<SessionTerminalView, bool>(nameof(IsRunning));
    public static readonly StyledProperty<bool> IsDoneProperty =
        AvaloniaProperty.Register<SessionTerminalView, bool>(nameof(IsDone));
    public static readonly StyledProperty<bool> IsFailedProperty =
        AvaloniaProperty.Register<SessionTerminalView, bool>(nameof(IsFailed));

    public IEnumerable? Entries { get => GetValue(EntriesProperty); set => SetValue(EntriesProperty, value); }
    public string? Label { get => GetValue(LabelProperty); set => SetValue(LabelProperty, value); }
    public bool IsRunning { get => GetValue(IsRunningProperty); set => SetValue(IsRunningProperty, value); }
    public bool IsDone { get => GetValue(IsDoneProperty); set => SetValue(IsDoneProperty, value); }
    public bool IsFailed { get => GetValue(IsFailedProperty); set => SetValue(IsFailedProperty, value); }

    private INotifyCollectionChanged? _subscribedCollection;

    public SessionTerminalView() { InitializeComponent(); }

    protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
    {
        base.OnPropertyChanged(change);
        if (change.Property != EntriesProperty) return;

        if (_subscribedCollection is not null)
            _subscribedCollection.CollectionChanged -= OnEntriesChanged;

        _subscribedCollection = change.NewValue as INotifyCollectionChanged;

        if (_subscribedCollection is not null)
            _subscribedCollection.CollectionChanged += OnEntriesChanged;
    }

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