using NexusShell.Models.Browser;

namespace NexusShell.Services;

public sealed class NexusTabService
{
    private readonly List<BrowserTab> _tabs = [];
    private BrowserTab? _activeTab;

    public IReadOnlyList<BrowserTab> Tabs => _tabs;

    public BrowserTab? ActiveTab => _activeTab;

    public event EventHandler? TabsChanged;
    public event EventHandler<BrowserTab>? ActiveTabChanged;

    public BrowserTab CreateTab(string? initialUrl = null)
    {
        var tab = new BrowserTab(Guid.NewGuid())
        {
            CurrentUrl = initialUrl ?? NexusBrowserConstants.HomeUrl,
            AddressText = initialUrl ?? string.Empty,
            Title = "Ny fane",
        };

        _tabs.Add(tab);
        SelectTab(tab);
        TabsChanged?.Invoke(this, EventArgs.Empty);
        return tab;
    }

    public bool CloseTab(BrowserTab tab)
    {
        if (_tabs.Count <= 1)
        {
            return false;
        }

        var index = _tabs.IndexOf(tab);
        if (index < 0)
        {
            return false;
        }

        _tabs.RemoveAt(index);
        if (_activeTab == tab)
        {
            var nextIndex = Math.Min(index, _tabs.Count - 1);
            SelectTab(_tabs[nextIndex]);
        }

        TabsChanged?.Invoke(this, EventArgs.Empty);
        return true;
    }

    public void SelectTab(BrowserTab tab)
    {
        if (!_tabs.Contains(tab))
        {
            return;
        }

        foreach (var existing in _tabs)
        {
            existing.IsActive = existing == tab;
        }

        _activeTab = tab;
        ActiveTabChanged?.Invoke(this, tab);
    }

    public BrowserTab? FindTab(Guid id) => _tabs.FirstOrDefault(t => t.Id == id);

    public void EnsureMinimumTabs()
    {
        if (_tabs.Count == 0)
        {
            CreateTab();
        }
    }
}
