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

namespace BackOffice.Pages.UserOrder.Components;

public partial class CancelOrderDialog
{
    [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 string? _cancelReason;
    private bool _refundPayment;
    private bool _isSaving;

    private async Task SubmitAsync()
    {
        if (string.IsNullOrWhiteSpace(_cancelReason))
        {
            Snackbar.Add("لطفاً دلیل لغو سفارش را وارد کنید.", Severity.Warning);
            return;
        }

        _isSaving = true;
        StateHasChanged();

        try
        {
            var request = new CancelOrderRequest
            {
                OrderId = OrderId,
                CancelReason = _cancelReason ?? string.Empty,
                RefundPayment = _refundPayment
            };

            var response = await UserOrderContract.CancelOrderAsync(request);

            var message = string.IsNullOrWhiteSpace(response.Message)
                ? "سفارش با موفقیت لغو شد."
                : response.Message;

            Snackbar.Add(message, Severity.Success);
            MudDialog.Close(DialogResult.Ok(true));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در لغو سفارش: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSaving = false;
            StateHasChanged();
        }
    }

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

