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!;

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

    protected override async Task OnInitializedAsync()
    {
        await LoadProductAsync();
    }

    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
        {
            await DiscountCartService.AddAsync(_product.Id, _quantity);
            Snackbar.Add($"{_product.Title} به سبد خرید اضافه شد", MudBlazor.Severity.Success);
        }
        catch
        {
            Snackbar.Add("خطا در افزودن به سبد خرید", MudBlazor.Severity.Error);
        }
        finally
        {
            _addingToCart = false;
        }
    }
}
