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

namespace BackOffice.Pages.UserOrder.Components;

public partial class ChangeOrderStatusDialog
{
    [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; }
    [Parameter] public int CurrentStatus { get; set; }
    [Parameter] public string? TrackingCode { get; set; }
    [Parameter] public string? DeliveryDescription { get; set; }

    private MudForm? _form;
    private bool _isValid;
    private int _newStatus;
    private string? _trackingCode;
    private string? _deliveryDescription;
    private bool _isSaving;

    protected override void OnInitialized()
    {
        _newStatus = CurrentStatus;
        _trackingCode = TrackingCode;
        _deliveryDescription = DeliveryDescription;
    }

    private string GetDeliveryStatusText(int status)
    {
        return status switch
        {
            1 => "در انتظار ارسال",
            2 => "تحویل پست",
            3 => "تحویل به مشتری",
            4 => "مرجوع شده",
            5 => "لغو شده",
            6 => "آماده تحویل در دفتر",
            _ => "بدون ارسال / نامشخص"
        };
    }

    private Color GetStatusColor(int status)
    {
        return status switch
        {
            1 => Color.Warning,
            2 => Color.Info,
            3 => Color.Success,
            4 => Color.Error,
            5 => Color.Dark,
            6 => Color.Primary,
            _ => Color.Default
        };
    }

    private async Task SubmitAsync()
    {
        if (_form != null)
        {
            await _form.Validate();
            if (!_isValid) return;
        }

        _isSaving = true;
        StateHasChanged();

        try
        {
            // Update delivery status
            var response = await UserOrderContract.UpdateOrderStatusAsync(new UpdateOrderStatusRequest
            {
                OrderId = OrderId,
                NewStatus = _newStatus
            });

            if (response.Success)
            {
                // Also update tracking code and description via UpdateUserOrder
                if (!string.IsNullOrEmpty(_trackingCode) || !string.IsNullOrEmpty(_deliveryDescription))
                {
                    try
                    {
                        var updateRequest = new UpdateUserOrderRequest
                        {
                            Id = OrderId,
                            TrackingCode = _trackingCode ?? string.Empty,
                            DeliveryDescription = _deliveryDescription ?? string.Empty
                        };
                        await UserOrderContract.UpdateUserOrderAsync(updateRequest);
                    }
                    catch
                    {
                        // Non-critical: status was already updated
                    }
                }

                Snackbar.Add("وضعیت ارسال سفارش با موفقیت به‌روزرسانی شد.", 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();
    }
}

