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 WarehousesPage
{
    [Inject] public InventoryContract.InventoryContractClient InventoryContract { get; set; } = default!;

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

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

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

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

    private async Task OpenCreateWarehouseDialog()
    {
        var dialog = await DialogService.ShowAsync<CreateWarehouseDialog>("ایجاد انبار جدید", new DialogOptions
        {
            CloseButton = true,
            MaxWidth = MaxWidth.Small,
            FullWidth = true
        });

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

    private void ViewWarehouseInventory(WarehouseDto warehouse)
    {
        Navigation.NavigateTo($"{RouteConstance.Inventory}?warehouseId={warehouse.Id}");
    }

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