@using CMSMicroservice.Protobuf.Protos.Inventory

<MudDialog>
    <DialogContent>
        <MudForm @ref="_form" @bind-IsValid="_formValid">
            <MudStack Spacing="4">
                <MudAlert Severity="Severity.Info">
                    <MudStack Spacing="1">
                        <MudText>محصول: <strong>@Item.ProductTitle</strong></MudText>
                        <MudText>موجودی فعلی: <strong>@Item.Quantity</strong> عدد</MudText>
                        <MudText>رزرو شده: <strong>@Item.ReservedQuantity</strong> عدد</MudText>
                        <MudText>قابل فروش: <strong>@Item.AvailableQuantity</strong> عدد</MudText>
                    </MudStack>
                </MudAlert>

                <MudNumericField T="int" @bind-Value="_newQuantity"
                                 Label="موجودی جدید"
                                 Variant="Variant.Outlined"
                                 Required="true"
                                 RequiredError="موجودی الزامی است"
                                 Min="0"
                                 HelperText="@GetDifferenceText()" />

                <MudTextField T="string" @bind-Value="_note"
                              Label="توضیحات (دلیل تغییر)"
                              Variant="Variant.Outlined"
                              Lines="3"
                              Required="true"
                              RequiredError="توضیحات الزامی است" />

                @if (_newQuantity != Item.Quantity)
                {
                    <MudAlert Severity="@(GetDifference() > 0 ? Severity.Success : Severity.Warning)">
                        @GetDifferenceAlertText()
                    </MudAlert>
                }
            </MudStack>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">انصراف</MudButton>
        <MudButton Color="Color.Primary"
                   Variant="Variant.Filled"
                   OnClick="Submit"
                   Disabled="@(!_formValid || _isSubmitting || _newQuantity == Item.Quantity)">
            @if (_isSubmitting)
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" Class="mr-2" />
            }
            ذخیره تغییرات
        </MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;
    [Inject] public InventoryContract.InventoryContractClient InventoryContract { get; set; } = default!;

    [Parameter] public InventoryItemDto Item { get; set; } = default!;

    private MudForm? _form;
    private bool _formValid;
    private bool _isSubmitting;

    private int _newQuantity;
    private string _note = string.Empty;

    protected override void OnInitialized()
    {
        _newQuantity = Item.Quantity;
    }

    private int GetDifference() => _newQuantity - Item.Quantity;

    private string GetDifferenceText()
    {
        var diff = GetDifference();
        if (diff == 0) return "بدون تغییر";
        return diff > 0 ? $"افزایش {diff} عدد" : $"کاهش {Math.Abs(diff)} عدد";
    }

    private string GetDifferenceAlertText()
    {
        var diff = GetDifference();
        if (diff > 0)
            return $"موجودی {diff} عدد افزایش می‌یابد (از {Item.Quantity} به {_newQuantity})";
        return $"موجودی {Math.Abs(diff)} عدد کاهش می‌یابد (از {Item.Quantity} به {_newQuantity})";
    }

    private void Cancel() => MudDialog.Cancel();

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

        if (_newQuantity == Item.Quantity)
        {
            Snackbar.Add("هیچ تغییری در موجودی انجام نشده است", Severity.Warning);
            return;
        }

        _isSubmitting = true;
        try
        {
            var productId = Item.ProductType == ProductType.RegularProduct 
                ? (Item.ProductId ?? 0) 
                : (Item.DiscountProductId ?? 0);

            var request = new AdjustStockRequest
            {
                ProductId = productId,
                ProductType = Item.ProductType,
                NewQuantity = _newQuantity,
                Reason = _note ?? string.Empty
            };

            var response = await InventoryContract.AdjustStockAsync(request);

            Snackbar.Add($"موجودی از {response.PreviousQuantity} به {response.NewQuantity} تغییر کرد (تفاوت: {response.Difference})", Severity.Success);
            MudDialog.Close(DialogResult.Ok(true));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSubmitting = false;
        }
    }
}
