using Microsoft.AspNetCore.Components;
using MudBlazor;
using CMSMicroservice.Protobuf.Protos.Inventory;
using BackOffice.Pages.Inventory.Components;
using BackOffice.Common.Utilities;

namespace BackOffice.Pages.Inventory;

public partial class LowStockPage
{
    [Inject] public InventoryContract.InventoryContractClient InventoryContract { get; set; } = default!;

    private List<InventoryItemDto> _items = new();
    private List<WarehouseDto> _warehouses = new();
    private bool _isLoading = true;

    // Filter fields
    private long? _filterWarehouseId;
    private ProductType _filterProductType = ProductType.Unspecified;

    protected override async Task OnInitializedAsync()
    {
        await LoadWarehouses();
        await LoadData();
    }

    private async Task LoadWarehouses()
    {
        try
        {
            var response = await InventoryContract.GetAllWarehousesAsync(new GetAllWarehousesRequest
            {
                IsActive = true
            });
            _warehouses = response.Warehouses.ToList();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری انبارها: {ex.Message}", Severity.Error);
        }
    }

    private async Task LoadData()
    {
        _isLoading = true;
        StateHasChanged();

        try
        {
            var request = new GetLowStockItemsRequest
            {
                Page = 1,
                PageSize = 200, // Get up to 200 low stock items
                ProductType = _filterProductType
            };

            if (_filterWarehouseId.HasValue)
            {
                request.WarehouseId = _filterWarehouseId.Value;
            }

            var response = await InventoryContract.GetLowStockItemsAsync(request);
            _items = response.Items.ToList();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری داده‌ها: {ex.Message}", Severity.Error);
            _items = new();
        }
        finally
        {
            _isLoading = false;
            StateHasChanged();
        }
    }

    private string GetProductTypeLabel(ProductType type)
    {
        return type switch
        {
            ProductType.RegularProduct => "محصول عادی",
            ProductType.DiscountProduct => "محصول تخفیفی",
            _ => "نامشخص"
        };
    }

    private async Task OpenAddStockDialog(InventoryItemDto item)
    {
        var productId = item.ProductType == ProductType.RegularProduct
            ? (item.ProductId ?? 0)
            : (item.DiscountProductId ?? 0);

        var parameters = new DialogParameters
        {
            ["Warehouses"] = _warehouses,
            ["ProductIdParam"] = productId,
            ["ProductTypeParam"] = item.ProductType,
            ["ProductName"] = item.ProductTitle,
            ["WarehouseIdParam"] = item.WarehouseId
        };

        var dialog = await DialogService.ShowAsync<AddStockDialog>($"ورود کالا - {item.ProductTitle}", parameters, new DialogOptions
        {
            CloseButton = true,
            MaxWidth = MaxWidth.Medium,
            FullWidth = true
        });

        var result = await dialog.Result;
        if (!result!.Canceled)
        {
            Snackbar.Add("موجودی با موفقیت اضافه شد", Severity.Success);
            await LoadData();
        }
    }

    private void GoBack()
    {
        Navigation.NavigateTo(RouteConstance.Inventory);
    }
}
