using CMSMicroservice.Protobuf.Protos.UserOrder;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace BackOffice.Pages.UserOrder.Components;

public partial class ApplyDiscountDialog
{
    [CascadingParameter] public IMudDialogInstance MudDialog { get; set; } = default!;
    [Inject] public UserOrderContract.UserOrderContractClient UserOrderContract { get; set; } = default!;
    // Snackbar is injected via _Imports.razor

    [Parameter] public long OrderId { get; set; }

    private long? _discountAmount;
    private string? _reason;
    private bool _isSaving;

    private async Task SubmitAsync()
    {
        if (!_discountAmount.HasValue || _discountAmount.Value <= 0)
        {
            Snackbar.Add("مبلغ تخفیف باید بزرگتر از صفر باشد.", Severity.Warning);
            return;
        }

        _isSaving = true;
        StateHasChanged();

        try
        {
            var request = new ApplyDiscountToOrderRequest
            {
                OrderId = OrderId,
                DiscountAmount = _discountAmount.Value,
                Reason = _reason ?? string.Empty
            };

            var response = await UserOrderContract.ApplyDiscountToOrderAsync(request);

            if (response.Success)
            {
                Snackbar.Add($"تخفیف با موفقیت اعمال شد. مبلغ نهایی: {response.FinalAmount.ToString("N0")} تومان", Severity.Success);
                MudDialog.Close(DialogResult.Ok(true));
            }
            else
            {
                var message = string.IsNullOrWhiteSpace(response.Message)
                    ? "اعمال تخفیف با خطا مواجه شد."
                    : response.Message;
                Snackbar.Add(message, Severity.Warning);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در اعمال تخفیف: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSaving = false;
            StateHasChanged();
        }
    }

    private void Cancel()
    {
        MudDialog.Cancel();
    }
}

