using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace FrontOffice.Main.Pages.Blog;

public partial class Index
{
    [Inject] private BlogPostService BlogPostService { get; set; } = default!;
    [Inject] private BlogCategoryService BlogCategoryService { get; set; } = default!;

    // ── State ──
    private List<BlogPostCardDto> _posts = new();
    private List<BlogCategoryDto> _categories = new();
    private string? _searchTerm;
    private long? _selectedCategoryId;
    private int _currentPage = 1;
    private int _totalPages;
    private bool _isLoading = true;
    private const int PageSize = 9;

    protected override async Task OnInitializedAsync()
    {
        // Load categories and posts in parallel
        var categoriesTask = BlogCategoryService.GetActiveCategoriesAsync();
        var postsTask = LoadPostsAsync();

        _categories = await categoriesTask;
        await postsTask;
    }

    private async Task LoadPostsAsync()
    {
        _isLoading = true;
        StateHasChanged();

        try
        {
            var result = await BlogPostService.GetPublishedPostsAsync(
                page: _currentPage,
                pageSize: PageSize,
                search: _searchTerm,
                categoryId: _selectedCategoryId);

            _posts = result.Posts;
            _totalPages = result.TotalPages;
        }
        catch
        {
            _posts = new();
            _totalPages = 0;
        }
        finally
        {
            _isLoading = false;
            StateHasChanged();
        }
    }

    private async Task SearchPosts()
    {
        _currentPage = 1;
        await LoadPostsAsync();
    }

    private async Task OnSearchKeyUp(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
        {
            await SearchPosts();
        }
    }

    private async Task OnCategoryChanged(long? categoryId)
    {
        _selectedCategoryId = categoryId;
        _currentPage = 1;
        await LoadPostsAsync();
    }

    private async Task OnPageChanged(int page)
    {
        _currentPage = page;
        await LoadPostsAsync();
    }

    private void NavigateToPost(string slug)
    {
        Navigation.NavigateTo($"/blog/{slug}");
    }
}
