using Microsoft.AspNetCore.Components;
using FrontOffice.Main.Utilities;
using System.Linq;

namespace FrontOffice.Main.Pages.Store;

public partial class Cart : ComponentBase, IDisposable
{
    [Inject] private CartService CartService { get; set; } = default!;
    [Inject] private VATService VAT { get; set; } = default!;
    [Inject] private AuthDialogService AuthDialogService { get; set; } = default!;
    [Inject] private AuthService AuthService { get; set; } = default!;
    // Navigation and Snackbar are available via _Imports.razor
    private CartService CartData => CartService;

    protected override async Task OnInitializedAsync()
    {
        if (!await AuthService.IsAuthenticatedAsync())
        {
            await AuthDialogService.ShowAuthDialogAsync();
        }
        // لود سبد خرید (فقط اگر کاربر لاگین کرده باشد)
        await CartService.EnsureInitializedAsync();
        CartService.OnChange += StateHasChanged;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // بارگذاری نرخ VAT
            await VAT.LoadAsync();
        }
        await base.OnAfterRenderAsync(firstRender);
    }

    private async Task IncrementQty(long productId)
    {
        var item = CartData.Items.FirstOrDefault(i => i.ProductId == productId);
        if (item is null) return;
        await CartService.UpdateQuantity(productId, item.Quantity + 1);
    }

    private async Task DecrementQty(long productId)
    {
        var item = CartData.Items.FirstOrDefault(i => i.ProductId == productId);
        if (item is null) return;
        await CartService.UpdateQuantity(productId, item.Quantity - 1);
    }

    private async Task ChangeQty(long productId, int value)
    {
        await CartService.UpdateQuantity(productId, value);
    }

    private async Task Remove(long cartId)
    {
        await CartService.Remove(cartId);
    }

    private void ProceedCheckout()
    {
        Navigation.NavigateTo(RouteConstants.Store.CheckoutSummary);
    }

    private string FormatPrice(long price) => $"{price:N0} ";
    
    private string FormatPriceWithVAT(long price) => $"{VAT.AddVAT(price):N0} ";
    
    private long TotalWithVAT => VAT.AddVAT(CartData.Total);
    
    private long VATAmount => VAT.CalculateVAT(CartData.Total);

    private static string GetProductImageUrl(string? imageUrl)
        => string.IsNullOrWhiteSpace(imageUrl) ? "/images/product-placeholder.svg" : imageUrl.TrimStart('/');

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