@using CMSMicroservice.Protobuf.Protos.Inventory
@using Google.Protobuf.WellKnownTypes
@using InventoryProductType = CMSMicroservice.Protobuf.Protos.Inventory.ProductType
@using BackOffice.Pages.AutoComplete

<MudDialog>
    <DialogContent>
        <MudForm @ref="_form" @bind-IsValid="_formValid">
            <MudGrid>
                @if (ProductIdParam == null)
                {
                    <MudItem xs="12">
                        <MudSelect T="InventoryProductType" @bind-Value="_productType"
                                   Label="نوع محصول"
                                   Variant="Variant.Outlined"
                                   Required="true"
                                   RequiredError="نوع محصول الزامی است">
                            <MudSelectItem T="InventoryProductType" Value="InventoryProductType.RegularProduct">محصول عادی</MudSelectItem>
                            <MudSelectItem T="InventoryProductType" Value="InventoryProductType.DiscountProduct">محصول تخفیفی</MudSelectItem>
                        </MudSelect>
                    </MudItem>
                    <MudItem xs="12">
                        @if (_productType == InventoryProductType.RegularProduct)
                        {
                            <ProductsAutoComplete @bind-Value="_productId"
                                                  Label="انتخاب محصول عادی" />
                        }
                        else
                        {
                            <DiscountProductsAutoComplete @bind-Value="_discountProductId"
                                                          Label="انتخاب محصول تخفیفی" />
                        }
                    </MudItem>
                }
                else
                {
                    <MudItem xs="12">
                        <MudAlert Severity="Severity.Info">
                            محصول: <strong>@ProductName</strong>
                        </MudAlert>
                    </MudItem>
                }

                <MudItem xs="12">
                    <MudSelect T="long?" @bind-Value="_warehouseId"
                               Label="انبار"
                               Variant="Variant.Outlined"
                               Required="true"
                               RequiredError="انبار الزامی است">
                        @foreach (var wh in Warehouses)
                        {
                            <MudSelectItem T="long?" Value="@((long?)wh.Id)">@wh.Name</MudSelectItem>
                        }
                    </MudSelect>
                </MudItem>

                <MudItem xs="12">
                    <MudNumericField T="int" @bind-Value="_quantity"
                                     Label="تعداد"
                                     Variant="Variant.Outlined"
                                     Required="true"
                                     RequiredError="تعداد الزامی است"
                                     Min="1" />
                </MudItem>

                <MudItem xs="12">
                    <MudTextField T="string" @bind-Value="_referenceNumber"
                                  Label="شماره مرجع (فاکتور/رسید)"
                                  Variant="Variant.Outlined" />
                </MudItem>

                <MudItem xs="12">
                    <MudTextField T="string" @bind-Value="_note"
                                  Label="توضیحات"
                                  Variant="Variant.Outlined"
                                  Lines="3" />
                </MudItem>
            </MudGrid>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">انصراف</MudButton>
        <MudButton Color="Color.Primary"
                   Variant="Variant.Filled"
                   OnClick="Submit"
                   Disabled="@(!_formValid || _isSubmitting)">
            @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 List<WarehouseDto> Warehouses { get; set; } = new();
    [Parameter] public long? ProductIdParam { get; set; }
    [Parameter] public InventoryProductType? ProductTypeParam { get; set; }
    [Parameter] public string? ProductName { get; set; }
    [Parameter] public long? WarehouseIdParam { get; set; }

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

    private InventoryProductType _productType = InventoryProductType.RegularProduct;
    private long? _productId;
    private long? _discountProductId;
    private long? _warehouseId;
    private int _quantity = 1;
    private string _referenceNumber = string.Empty;
    private string _note = string.Empty;

    protected override void OnInitialized()
    {
        if (ProductIdParam.HasValue && ProductTypeParam.HasValue)
        {
            if (ProductTypeParam.Value == InventoryProductType.DiscountProduct)
                _discountProductId = ProductIdParam.Value;
            else
                _productId = ProductIdParam.Value;
        }
        if (ProductTypeParam.HasValue)
        {
            _productType = ProductTypeParam.Value;
        }
        if (WarehouseIdParam.HasValue)
        {
            _warehouseId = WarehouseIdParam.Value;
        }
    }

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

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

        if (!_warehouseId.HasValue)
        {
            Snackbar.Add("لطفاً انبار را انتخاب کنید", Severity.Warning);
            return;
        }

        _isSubmitting = true;
        try
        {
            var selectedProductId = ProductIdParam 
                ?? (_productType == InventoryProductType.DiscountProduct ? _discountProductId : _productId);

            if (!selectedProductId.HasValue || selectedProductId.Value <= 0)
            {
                Snackbar.Add("لطفاً یک محصول انتخاب کنید", Severity.Warning);
                _isSubmitting = false;
                return;
            }

            var request = new AddStockRequest
            {
                ProductId = selectedProductId.Value,
                ProductType = ProductTypeParam ?? _productType,
                Quantity = _quantity,
                ReferenceNumber = _referenceNumber ?? string.Empty,
                Note = _note ?? string.Empty,
                WarehouseId = _warehouseId.Value
            };

            var response = await InventoryContract.AddStockAsync(request);

            Snackbar.Add($"موجودی جدید: {response.NewQuantity} عدد", Severity.Success);
            MudDialog.Close(DialogResult.Ok(true));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSubmitting = false;
        }
    }
}
