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

namespace FrontOffice.Main.Pages.DiscountStore;

public partial class Products : ComponentBase, IDisposable
{
    [Inject] private DiscountProductService ProductService { get; set; } = default!;
    [Inject] private DiscountCartService DiscountCart { get; set; } = default!;

    private string _search = string.Empty;
    private long? _selectedCategoryId;
    private int _currentPage = 1;
    private bool _loading;
    private const int PageSize = 12;

    private DiscountProductListResult _result = new(new(), 0, 0, 1);
    private List<DiscountCategoryNode> _categories = new();

    protected override async Task OnInitializedAsync()
    {
        _loading = true;
        await DiscountCart.EnsureInitializedAsync();
        DiscountCart.OnChange += StateHasChanged;
        var categoriesTask = ProductService.GetCategoriesAsync();
        var productsTask = ProductService.GetProductsAsync(page: 1, pageSize: PageSize);
        await Task.WhenAll(categoriesTask, productsTask);
        _categories = categoriesTask.Result;
        _result = productsTask.Result;
        _loading = false;
    }

    private async Task LoadProductsAsync()
    {
        _loading = true;
        StateHasChanged();
        _result = await ProductService.GetProductsAsync(
            page: _currentPage,
            pageSize: PageSize,
            search: string.IsNullOrWhiteSpace(_search) ? null : _search,
            categoryId: _selectedCategoryId);
        _loading = false;
        StateHasChanged();
    }

    private async Task SearchProducts() => await LoadProductsAsync();

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

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

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

    private async Task AddToCart(DiscountProductCard p)
    {
        await DiscountCart.AddAsync(p.Id);
    }

    private void NavigateToProduct(long id)
    {
        Navigation.NavigateTo($"{RouteConstants.DiscountStore.ProductDetail}{id}");
    }

    private static string FormatPrice(long price) => $"{price:N0} تومان";

    public void Dispose()
    {
        DiscountCart.OnChange -= StateHasChanged;
    }
}
