using BookReader.Services;
using BookReader.ViewModels;

namespace BookReader.Views;

public partial class BookshelfPage : ContentPage
{
    private readonly BookshelfViewModel _viewModel;
    private readonly INavigationService _navigationService;

    public BookshelfPage(BookshelfViewModel viewModel, INavigationService navigationService, ICachedImageLoadingService imageLoadingService)
    {
        InitializeComponent();
        _viewModel = viewModel;
        _navigationService = navigationService;
        BindingContext = viewModel;
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        // Загружаем книги только если коллекция пуста
        if (_viewModel.Books.Count == 0)
        {
            _ = _viewModel.LoadBooksCommand.ExecuteAsync(null);
        }
    }

    protected override async void OnNavigatedTo(NavigatedToEventArgs args)
    {
        base.OnNavigatedTo(args);
        
        // Если вернулись на главную страницу и книги уже загружены - обновляем прогресс
        // (например, после чтения)
        if (_viewModel.Books.Count > 0 && !_viewModel.IsBusy)
        {
            await _viewModel.LoadBooksCommand.ExecuteAsync(null);
        }
    }

    private async void OnMenuClicked(object? sender, EventArgs e)
    {
        var action = await _navigationService.DisplayActionSheetAsync("Menu", "Cancel",
            "⚙️ Settings", "☁️ Calibre Library", "ℹ️ About");

        switch (action)
        {
            case "⚙️ Settings":
                await _viewModel.OpenSettingsCommand.ExecuteAsync(null);
                break;
            case "☁️ Calibre Library":
                await _viewModel.OpenCalibreLibraryCommand.ExecuteAsync(null);
                break;
            case "ℹ️ About":
                await _navigationService.DisplayAlertAsync("About", "BookReader v1.0\nEPUB & FB2 Reader", "OK");
                break;
        }
    }
}