using Microsoft.AspNetCore.Components;

namespace NexusReader.UI.Shared.Services;

public class ReaderNavigationService : IReaderNavigationService
{
    private readonly NavigationManager _navigationManager;

    public ReaderNavigationService(NavigationManager navigationManager)
    {
        _navigationManager = navigationManager;
    }

    public Guid CurrentEbookId { get; private set; } = Guid.Empty;
    public int CurrentChapterIndex { get; private set; } = 0;
    public int TotalChapters { get; private set; } = 1;
    public string ChapterTitle { get; private set; } = "Loading...";
    public string? PendingScrollBlockId { get; set; }

    public event Func<Task>? OnNavigationChanged;

    public async Task GoToChapter(int index)
    {
        if (index < 0 || index >= TotalChapters) return;

        CurrentChapterIndex = index;
        await NotifyNavigationChangedAsync();
    }

    public async Task GoToNextChapter()
    {
        if (CurrentChapterIndex < TotalChapters - 1)
        {
            await GoToChapter(CurrentChapterIndex + 1);
        }
    }

    public async Task GoToPreviousChapter()
    {
        if (CurrentChapterIndex > 0)
        {
            await GoToChapter(CurrentChapterIndex - 1);
        }
    }

    public async Task UpdateMetadataAsync(int currentIndex, int totalChapters, string title)
    {
        bool changed = false;
        if (CurrentChapterIndex != currentIndex) { CurrentChapterIndex = currentIndex; changed = true; }
        if (TotalChapters != totalChapters) { TotalChapters = totalChapters; changed = true; }
        if (ChapterTitle != title) { ChapterTitle = title; changed = true; }

        if (changed)
        {
            await NotifyNavigationChangedAsync();
        }
    }

    public void NavigateToBook(Guid bookId)
    {
        CurrentEbookId = bookId;
        CurrentChapterIndex = 0;
        _navigationManager.NavigateTo($"/reader/{bookId}");
    }

    public void SetBook(Guid bookId, int chapterIndex = 0)
    {
        CurrentEbookId = bookId;
        CurrentChapterIndex = chapterIndex;
    }

    private async Task NotifyNavigationChangedAsync()
    {
        var handlers = OnNavigationChanged?.GetInvocationList();
        if (handlers != null)
        {
            foreach (var handler in handlers.Cast<Func<Task>>())
            {
                await handler();
            }
        }
    }
}
