@using AyCode.Core.Extensions
@using AyCode.Utils.Extensions
@using DevExpress.Blazor
@using FruitBank.Common.Dtos
@using FruitBank.Common.Entities
@using FruitBank.Common.Helpers
@using FruitBank.Common.Models
@using FruitBank.Common.SignalRs
@using FruitBankHybrid.Shared.Databases
@using FruitBankHybrid.Shared.Extensions
@using FruitBankHybrid.Shared.Services
@using FruitBankHybrid.Shared.Services.SignalRs
@using Mango.Nop.Core.Entities

<DxLoadingPanel @bind-Visible="LoadingPanelVisible"
                IsContentBlocked="true"
                ApplyBackgroundShading="true"
                IndicatorAreaVisible="true"
                IsContentVisible="true"
                IndicatorAnimationType="WaitIndicatorAnimationType.Spin"
                Text="Adatok szinkronizálása folyamatban...">

<DxFormLayout CaptionPosition="CaptionPosition.Vertical" CssClass="w-100">
	<DxFormLayoutItem Caption="Termék:" ColSpanMd="2">
		@* CaptionCssClass="@(SelectedProductDto?.IsMeasured == true ? "text-success" : "")"> *@
		<DxComboBox @ref="cbStockTakings"
					Data="@_stockTakings"
					TextFieldName="@nameof(StockTaking.StartDateTime)"
					CssClass="cw-480"
					DropDownBodyCssClass="dd-body-class"
					Context="ctxProduct"
					InputId="cbProduct"
					Value="@SelectedStockTaking"
					ValueChanged="@(async (StockTaking stockTaking) => await StockTakingComboValueChanged(stockTaking, null))">
		</DxComboBox>
	</DxFormLayoutItem>
	<DxFormLayoutItem ColSpanMd="4">
		<DxComboBox Data="@_stockTakingItems"
					@bind-Value="@SelectedStockTakingItem"
					TextFieldName="@nameof(StockTakingItem.DisplayText)"
					CssClass="cw-480"
					DropDownBodyCssClass="dd-body-class"
					Context="ctxProduct2"
					InputId="cbProduct2"
					SearchMode="ListSearchMode.AutoSearch"
					SearchFilterCondition="ListSearchFilterCondition.Contains"
					SearchTextParseMode="ListSearchTextParseMode.Default"
					ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto"
					DropDownTriggerMode="DropDownTriggerMode.Click"
					@ref="cbStockTakingItems">
		</DxComboBox>
	</DxFormLayoutItem>
	@* TextFieldName="StockTakingItem.Product.Name" *@
	<DxFormLayoutItem ColSpanMd="1">
		<DxButton Text="Új" Enabled="@(!_btnDisabled && _stockTakings.All(x => x.IsClosed))" Click="() => NewStockTakingClick()"></DxButton>
	</DxFormLayoutItem>
@* 	<DxFormLayoutItem ColSpanMd="1">
		<DxButton Text="Módosít" Enabled="@((SelectedStockTaking?.IsClosed ?? false) && false)" Click="() => UpdateStockTakingClick()"></DxButton>
	</DxFormLayoutItem>
 *@	<DxFormLayoutItem ColSpanMd="1">
		<DxButton Text="Lezárás" Enabled="@(!_btnDisabled && (!SelectedStockTaking?.IsClosed ?? false) && (SelectedStockTaking?.IsReadyForClose() ?? false))" Click="() => StockTakingCloseClick(SelectedStockTaking!.Id)"></DxButton>
	</DxFormLayoutItem>

</DxFormLayout>

<div style="margin-top: 50px;">
	@if (SelectedStockTakingItem is { ProductId: > 0 })
	{
		<h3 style="margin-bottom: 30px;" class="@(SelectedStockTakingItem.IsMeasured && SelectedStockTakingItem.StockTakingItemPallets!.All(x => x.IsMeasuredAndValid(SelectedStockTakingItem.IsMeasurable)) ? "text-success" : "")">
			#@(SelectedStockTakingItem.ProductId). @(SelectedStockTakingItem.Product!.Name)
		</h3>

		<div>
			@{
				var a = $"Várható rekesz: {SelectedStockTakingItem.TotalOriginalQuantity} ({SelectedStockTakingItem.OriginalStockQuantity} + {SelectedStockTakingItem.InProcessOrdersQuantity}), Várható net.súly: {SelectedStockTakingItem.OriginalNetWeight} kg.";
				<span>@a</span>
			}

			@if (SelectedStockTakingItem.IsInvalid)
			{
				<div class="text-danger" style="margin-top: 15px">A várható mennyiség nem lehet negatív! A hibás adatok javítása után nyomja meg a "Frissítés" gombot.</div>
				<DxButton Text="Frissítés" Click="() => RefreshErrorItemClick(SelectedStockTakingItem)"></DxButton>
			}

		</div>
		<DxFormLayout Data="@SelectedStockTakingItem" CaptionPosition="CaptionPosition.Vertical" CssClass="w-100" Enabled="@((!SelectedStockTaking?.IsClosed ?? false))">
			<DxFormLayoutItem Context="ctxShippingItemFromLayoutItem" ColSpanMd="12">
				@for (var index = 0; index < (SelectedStockTakingItem?.StockTakingItemPallets?.Count ?? 0); index++)
				{
					var localI = index + 1;
					var currentShippingItemPallet = SelectedStockTakingItem!.StockTakingItemPallets![index];

					<PalletItemComponent IsMeasurable="@SelectedStockTakingItem!.IsMeasurable"
										 MeasuringIndex="@localI"
										 Editable="@(!SelectedStockTaking?.IsClosed ?? false)"
										 PalletItem="@currentShippingItemPallet"
										 ProductId="@SelectedStockTakingItem.Product!.Id"
										 AddOrUpdateSignalRTag="SignalRTags.AddOrUpdateMeasuredStockTakingItemPallet"
										 OnPalletItemSaved="pallet => OnStockTakingItemPalletSaved(pallet)"
										 OnPalletItemValueChanged="pallet => OnStockTakingItemPalletValueChanged(pallet, SelectedStockTakingItem)">
					</PalletItemComponent>
				}
			</DxFormLayoutItem>

			@* 			<DxFormLayoutItem Context="vfdfgfd" ColSpanMd="12" BeginRow="true">
				<DxFormLayout CssClass="w-100">
					<DxFormLayoutItem ColSpanMd="1" BeginRow="false"><strong>TOTAL:</strong></DxFormLayoutItem>
					<DxFormLayoutItem ColSpanMd="2" BeginRow="false" Visible="@(SelectedStockTakingItem.IsMeasurable)" />
					<DxFormLayoutItem ColSpanMd="2" BeginRow="false" Visible="@(SelectedStockTakingItem.IsMeasurable)" />
					<DxFormLayoutItem ColSpanMd="2" BeginRow="false"><strong>Rekesz: @(SelectedStockTakingItem.MeasuredStockQuantity) db</strong></DxFormLayoutItem>
					<DxFormLayoutItem ColSpanMd="2" BeginRow="false" Visible="@(SelectedStockTakingItem.IsMeasurable)"><strong>Br: @(SelectedStockTakingItem.MeasuredGrossWeight) kg</strong></DxFormLayoutItem>
					<DxFormLayoutItem ColSpanMd="1" BeginRow="false" Visible="@(SelectedStockTakingItem.IsMeasurable)"><strong>Net: @(SelectedStockTakingItem.MeasuredNetWeight) kg</strong></DxFormLayoutItem>
					<DxFormLayoutItem ColSpanMd="1" BeginRow="false" />
				</DxFormLayout>
			</DxFormLayoutItem>
 *@
		</DxFormLayout>
	}
</div>
</DxLoadingPanel>

@code
{
	[Inject] public required DatabaseClient Database { get; set; }
	[Inject] public required LoggedInModel LoggedInModel { get; set; }
	[Inject] public required IDialogService DialogService { get; set; } = null!;
	[Inject] public required FruitBankSignalRClient FruitBankSignalRClient { get; set; }

	bool _btnDisabled = false;
	bool LoadingPanelVisible = false;

	DxComboBox<StockTaking, StockTaking> cbStockTakings;
	DxComboBox<StockTakingItem, StockTakingItem> cbStockTakingItems;

	List<StockTaking> _stockTakings { get; set; } = [];
	List<StockTakingItem> _stockTakingItems { get; set; } = [];
	List<StockTakingItemPallet> _stockTakingItemPallets { get; set; } = [];
	StockTaking? SelectedStockTaking { get; set; }
	StockTakingItem? SelectedStockTakingItem { get; set; }

	protected override async Task OnInitializedAsync()
	{
		await ReloadDataFromDb(false);
	}

	public async Task ReloadDataFromDb(bool forceReload)
	{
		LoadingPanelVisible = true;

		_stockTakings = await FruitBankSignalRClient.GetStockTakings(false) ?? [];
		await StockTakingComboValueChanged(_stockTakings.FirstOrDefault(), null);

		LoadingPanelVisible = false;
	}

	private async Task RefreshErrorItemClick(StockTakingItem errorTakingItem)
	{
		var stockTakingItem = await FruitBankSignalRClient.RefreshStockTakingItem(errorTakingItem.Id);
		if (stockTakingItem == null)
		{
			await DialogService.ShowMessageBoxAsync("Hiba", "Adatok frissése sikertelen volt!", MessageBoxRenderStyle.Danger);
			return;
		}

		await StockTakingComboValueChanged(SelectedStockTaking, stockTakingItem.Id);

		if (stockTakingItem.IsInvalid)
			await DialogService.ShowMessageBoxAsync("Figyelem", "A termék továbbra is hibás!", MessageBoxRenderStyle.Warning);
	}

	private async Task NewStockTakingClick()
	{
		_btnDisabled = true;

		try
		{
			LoadingPanelVisible = true;

			var stockTaking = new StockTaking
			{
				StartDateTime = DateTime.Now,
				Creator = LoggedInModel.CustomerDto!.Id
			};

			var resultStockTakings = await FruitBankSignalRClient.AddStockTaking(stockTaking);
			if (resultStockTakings == null)
			{
				await DialogService.ShowMessageBoxAsync("Hiba", "Új leltár létrehozása sikertelen volt!", MessageBoxRenderStyle.Danger);
				return;
			}

			_stockTakings.UpdateCollection(resultStockTakings, false);
			await StockTakingComboValueChanged(_stockTakings.FirstOrDefault(x => x.Id == resultStockTakings.Id), null);
		}
		finally
		{
			_btnDisabled = false;
			LoadingPanelVisible = false;
		}

		//cbStockTakings.Reload();
		await InvokeAsync(StateHasChanged);
	}

	private async Task StockTakingCloseClick(int stockTakingId)
	{
		_btnDisabled = true;

		try
		{
			LoadingPanelVisible = true;

			var resultStockTaking = await FruitBankSignalRClient.CloseStockTaking(stockTakingId);
			if (resultStockTaking == null)
			{
				await DialogService.ShowMessageBoxAsync("Hiba", "A leltár lezárása sikertelen volt, ellenőrizze a leltár adatait!", MessageBoxRenderStyle.Danger);
				return;
			}

			_stockTakings.UpdateCollection(resultStockTaking, false);
			await StockTakingComboValueChanged(_stockTakings.FirstOrDefault(x => x.Id == resultStockTaking.Id), null);
		}
		finally
		{
			_btnDisabled = false;
			LoadingPanelVisible = false;
		}

		await InvokeAsync(StateHasChanged);
	}

	private async Task StockTakingComboValueChanged(StockTaking? newValue, int? selectedStockTakingItemId)
	{
		SelectedStockTaking = newValue;
		SelectedStockTaking?.StockTakingItems = await FruitBankSignalRClient.GetStockTakingItemsByStockTakingId(SelectedStockTaking.Id);

		PrepareStockTakingItems(SelectedStockTaking);

		SelectedStockTakingItem = selectedStockTakingItemId.HasValue ? _stockTakingItems.FirstOrDefault(x => x.Id == selectedStockTakingItemId.Value) : _stockTakingItems.FirstOrDefault();

		await InvokeAsync(StateHasChanged);
	}

	private void PrepareStockTakingItems(StockTaking? stockTaking)
	{
		_stockTakingItems = stockTaking?.StockTakingItems?
			.OrderByDescending(x => x.IsInvalid)
			.ThenByDescending(x => x.IsRequiredForMeasuring)
			.ThenBy(x => x.Product?.Name)
			.ToList() ?? [];

		foreach (var stockTakingItem in _stockTakingItems)
		{
			stockTakingItem.StockTakingItemPallets ??= [];
			stockTakingItem.StockTaking = stockTaking;

			if (!stockTakingItem.IsInvalid && stockTakingItem.StockTakingItemPallets.Count == 0)
			{
				stockTakingItem.StockTakingItemPallets.Add(MeasurementService.CreateNewStockTakingItemPallet(stockTakingItem, LoggedInModel.CustomerDto));
			}
			else
			{
				foreach (var stockTakingItemPallet in stockTakingItem.StockTakingItemPallets)
					stockTakingItemPallet.StockTakingItem = stockTakingItem;
			}
		}
	}

	private async Task OnStockTakingItemPalletValueChanged(StockTakingItemPallet stockTakingItemPallet, StockTakingItem stockTakingItem)
	{
		// MeasuringValuesHelper.SetShippingItemTotalMeasuringValues(stockTakingItem);
		// BtnSaveEnabled = stockTakingItem.IsValidMeasuringValues() && stockTakingItemPallet.IsValidMeasuringValues(stockTakingItem.IsMeasurable);

		//cbStockTakingItems.Reload();
		await InvokeAsync(StateHasChanged);
		//return Task.CompletedTask;
	}

	private async Task OnStockTakingItemPalletSaved(StockTakingItemPallet? responseStockTakingItemPallet)
	{
		if (responseStockTakingItemPallet != null)
		{
			//responseStockTakingItemPallet.IsMeasured = true;

			responseStockTakingItemPallet.StockTakingItem = SelectedStockTakingItem;
			SelectedStockTakingItem!.MeasuredStockQuantity = responseStockTakingItemPallet.TrayQuantity;

			if (SelectedStockTakingItem.IsMeasurable) SelectedStockTakingItem.MeasuredNetWeight = responseStockTakingItemPallet.NetWeight;

			SelectedStockTakingItem.StockTakingItemPallets!.UpdateCollection(responseStockTakingItemPallet, false);
			SelectedStockTakingItem.IsMeasured = SelectedStockTakingItem.StockTakingItemPallets!.All(sip => sip.IsMeasuredAndValid(SelectedStockTakingItem.IsMeasurable));

			// MeasuringValuesHelper.SetShippingItemTotalMeasuringValues(SelectedShippingItem);
		}
		else await DialogService.ShowMessageBoxAsync("Hiba", "Adatok mentése sikertelen volt, ellenőrizze a mérés adatait!", MessageBoxRenderStyle.Danger);

		//cbStockTakingItems.Reload();
		await InvokeAsync(StateHasChanged);

		await cbStockTakingItems.FocusAsync();
	}

}
