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

namespace FrontOffice.Main.Pages.DiscountStore;

public partial class ProductDetail
{
    [Parameter] public long Id { get; set; }

    [Inject] private DiscountProductService DiscountProductService { get; set; } = default!;
    [Inject] private DiscountCartService DiscountCartService { get; set; } = default!;
    [Inject] private VATService VAT { get; set; } = default!;
    [Inject] private GuestActionGate GuestGate { get; set; } = default!;
    [Inject] private AuthService AuthService { get; set; } = default!;

    private bool _isAuthenticated;

    private DiscountProductDetail? _product;
    private string _selectedImage = string.Empty;
    private int _quantity = 1;
    private bool _loading = true;
    private bool _addingToCart;

    protected override async Task OnInitializedAsync()
    {
        _isAuthenticated = await AuthService.IsAuthenticatedAsync();
        await LoadProductAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await VAT.LoadAsync();
            StateHasChanged();
        }
    }

    private async Task LoadProductAsync()
    {
        _loading = true;
        try
        {
            _product = await DiscountProductService.GetByIdAsync(Id);
            if (_product is not null)
            {
                _selectedImage = _product.Images.FirstOrDefault()?.ImageUrl
                                 ?? _product.ThumbnailUrl;
            }
        }
        catch
        {
            Snackbar.Add("خطا در بارگذاری محصول", MudBlazor.Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private async Task AddToCart()
    {
        if (_product is null) return;
        _addingToCart = true;
        try
        {
            var productId = _product.Id;
            var qty = _quantity;
            var title = _product.Title;
            await GuestGate.RunAsync(async () =>
            {
                await DiscountCartService.AddAsync(productId, qty);
                Snackbar.Add($"{title} به سبد خرید اضافه شد", MudBlazor.Severity.Success);
            });
        }
        catch
        {
            Snackbar.Add("خطا در افزودن به سبد خرید", MudBlazor.Severity.Error);
        }
        finally
        {
            _addingToCart = false;
        }
    }
}
