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!;
    [Inject] private GuestActionGate GuestGate { get; set; } = default!;

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

    private List<DiscountProductCard> _products = new();
    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;
        var result = productsTask.Result;
        _products = result.Products;
        _totalCount = result.TotalCount;
        _hasMore = result.CurrentPage < result.TotalPages;
        _loading = false;
    }

    private async Task LoadInitial()
    {
        _loading = true;
        _currentPage = 1;
        _products.Clear();
        StateHasChanged();
        
        var result = await ProductService.GetProductsAsync(
            page: 1,
            pageSize: PageSize,
            search: string.IsNullOrWhiteSpace(_search) ? null : _search,
            categoryId: _selectedCategoryId);
        _products = result.Products;
        _totalCount = result.TotalCount;
        _hasMore = result.CurrentPage < result.TotalPages;
        _loading = false;
        StateHasChanged();
    }

    private async Task LoadMore()
    {
        if (_loadingMore || !_hasMore) return;
        
        _loadingMore = true;
        StateHasChanged();
        
        _currentPage++;
        var result = await ProductService.GetProductsAsync(
            page: _currentPage,
            pageSize: PageSize,
            search: string.IsNullOrWhiteSpace(_search) ? null : _search,
            categoryId: _selectedCategoryId);
        _products.AddRange(result.Products);
        _hasMore = result.CurrentPage < result.TotalPages;
        
        _loadingMore = false;
        StateHasChanged();
    }

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

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

    private async Task OnCategoryChanged(long? value)
    {
        _selectedCategoryId = value;
        await LoadInitial();
    }

    private async Task AddToCart(DiscountProductCard p)
    {
        await GuestGate.RunAsync(() => 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;
    }
}
