@using System.Collections.ObjectModel
@using AyCode.Blazor.Components.Components.Grids
@using AyCode.Core.Helpers
@using AyCode.Core.Loggers
@using AyCode.Utils.Extensions
@using FruitBank.Common.Dtos
@using FruitBank.Common.Entities
@using FruitBankHybrid.Shared.Components.Grids.Shippings
@using FruitBankHybrid.Shared.Databases
@using FruitBankHybrid.Shared.Extensions
@using FruitBankHybrid.Shared.Services.Loggers
@using FruitBankHybrid.Shared.Services.SignalRs

@inject IEnumerable<IAcLogWriterClientBase> LogWriters
@inject FruitBankSignalRClient FruitBankSignalRClient

@* <GridShippingBase @ref="Grid" Data="Shippings" AutoSaveLayoutName="GridShipping"> *@

<MgGridWithInfoPanel ShowInfoPanel="@IsMasterGrid">
	<GridContent>
		<GridShippingBase @ref="Grid" DataSource="Shippings" AutoSaveLayoutName="GridShipping" SignalRClient="FruitBankSignalRClient" Logger="_logger"
						  CssClass="@GridCss" ValidationEnabled="false"
						  OnGridEditModelSaving="Grid_EditModelSaving"
						  OnGridFocusedRowChanged="Grid_FocusedRowChanged">
			<Columns>
				<DxGridDataColumn FieldName="Id" SortIndex="0" SortOrder="GridColumnSortOrder.Descending" ReadOnly="true" />
				<DxGridDataColumn FieldName="ShippingDate" Caption="Beérkezés" />
				<DxGridDataColumn FieldName="CargoPartnerId" Caption="Fuvarozó">
					<EditSettings>
						<DxComboBoxSettings Data="CargoPartners"
											ValueFieldName="Id"
											TextFieldName="Name"
											DropDownBodyCssClass="dd-body-class"
											ListRenderMode="ListRenderMode.Entire"
											SearchMode="ListSearchMode.AutoSearch"
											SearchFilterCondition="ListSearchFilterCondition.Contains"
											ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto">
							<Columns>
								<DxListEditorColumn FieldName="@nameof(CargoPartner.Id)" />
								<DxListEditorColumn FieldName="@nameof(CargoPartner.Name)" />
								<DxListEditorColumn FieldName="@nameof(CargoPartner.TaxId)" />
							</Columns>
						</DxComboBoxSettings>
					</EditSettings>
				</DxGridDataColumn>
				<DxGridDataColumn FieldName="CargoTruckId" Caption="Vontató">
					<EditSettings>
						<DxComboBoxSettings Data="CargoTrucks.Where(x => !x.IsTrailer)"
											ValueFieldName="Id"
											TextFieldName="LicencePlate"
											DropDownBodyCssClass="dd-body-class"
											ListRenderMode="ListRenderMode.Entire"
											SearchMode="ListSearchMode.AutoSearch"
											SearchFilterCondition="ListSearchFilterCondition.Contains"
											ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto">
							<Columns>
								<DxListEditorColumn FieldName="@nameof(CargoTruck.Id)" />
								<DxListEditorColumn FieldName="@nameof(CargoTruck.CargoPartnerName)" />
								<DxListEditorColumn FieldName="@nameof(CargoTruck.LicencePlate)" />
								<DxListEditorColumn FieldName="@nameof(CargoTruck.IsTrailer)" />
							</Columns>
						</DxComboBoxSettings>
					</EditSettings>
				</DxGridDataColumn>
				<DxGridDataColumn FieldName="CargoTrailerId" Caption="Utánfutó">
					<EditSettings>
						<DxComboBoxSettings Data="CargoTrucks.Where(x => x.IsTrailer)"
											ValueFieldName="Id"
											TextFieldName="LicencePlate"
											DropDownBodyCssClass="dd-body-class"
											ListRenderMode="ListRenderMode.Entire"
											SearchMode="ListSearchMode.AutoSearch"
											SearchFilterCondition="ListSearchFilterCondition.Contains"
											ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto">
							<Columns>
								<DxListEditorColumn FieldName="@nameof(CargoTruck.Id)" />
								<DxListEditorColumn FieldName="@nameof(CargoTruck.CargoPartnerName)" />
								<DxListEditorColumn FieldName="@nameof(CargoTruck.LicencePlate)" />
								<DxListEditorColumn FieldName="@nameof(CargoTruck.IsTrailer)" />
							</Columns>
						</DxComboBoxSettings>
					</EditSettings>
				</DxGridDataColumn>

				<DxGridDataColumn FieldName="LicencePlate" Caption="Rendszám" />
				<DxGridDataColumn FieldName="Comment" Caption="Megjegyzés" ReadOnly="false" />
				<DxGridDataColumn FieldName="CargoCompany" Caption="Fuvarozó" ReadOnly="false" />
				<DxGridDataColumn FieldName="IsAllMeasured" Caption="Mérések kész" ReadOnly="true" />
				<DxGridDataColumn FieldName="Created" Caption="Létrehozva" ReadOnly="true" />
				<DxGridDataColumn FieldName="Modified" Caption="Módosítva" ReadOnly="true" />
				<DxGridCommandColumn Visible="!IsMasterGrid" Width="120"></DxGridCommandColumn>
			</Columns>
			<DetailRowTemplate>
				@if (IsMasterGrid)
				{
					var shipping = ((Shipping)context.DataItem);
					var shippingDocuments = shipping?.ShippingDocuments ?? [];

					<DxTabs ActiveTabIndexChanged="(i) => OnActiveTabChanged(i)">
						<DxTabPage Text="Szállítólevelek">
							@{
								var observableShippingDocuments = new AcObservableCollection<ShippingDocument>(shippingDocuments);
								<GridShippingDocument ShippingDocuments="@observableShippingDocuments" ParentDataItem="@shipping" Partners="@Partners"></GridShippingDocument>
							}
						</DxTabPage>

						<DxTabPage Text="Szállítmány tételek">
							@{
								var observableShippingItems = new AcObservableCollection<ShippingItem>(shippingDocuments.SelectMany(sd => sd.ShippingItems ?? []));
								<GridShippingItemTemplate ShippingItems="@observableShippingItems" ParentDataItem="@shipping" />
							}
						</DxTabPage>
					</DxTabs>
				}
			</DetailRowTemplate>
			<ToolbarTemplate>
				@if (IsMasterGrid)
				{
					<MgGridToolbarTemplate Grid="Grid" OnReloadDataClick="() => ReloadDataFromDb(true)" />
				}
			</ToolbarTemplate>
		</GridShippingBase>
	</GridContent>
</MgGridWithInfoPanel>

@code {
	//[Inject] public required ObjectLock ObjectLock { get; set; }
	[Inject] public required DatabaseClient Database { get; set; }

	[Parameter] public bool IsMasterGrid { get; set; } = false;
	[Parameter] public AcObservableCollection<Partner>? Partners { get; set; }
	[Parameter] public AcObservableCollection<CargoPartner>? CargoPartners { get; set; }
	[Parameter] public AcObservableCollection<Shipping>? Shippings { get; set; }
	[Inject] public required IDialogService DialogService { get; set; } = null!;

	public List<CargoTruck> CargoTrucks { get; set; } = [];

	const string ExportFileName = "ExportResult";
	string GridSearchText = "";
	bool EditItemsEnabled { get; set; }
	int FocusedRowVisibleIndex { get; set; }
	public GridShippingBase Grid { get; set; }
	string GridCss => !IsMasterGrid ? "hide-toolbar" : string.Empty;

	private int _activeTabIndex;
	private LoggerClient<GridShipping> _logger;

	protected override async Task OnInitializedAsync()
	{
		_logger = new LoggerClient<GridShipping>(LogWriters.ToArray());
		await ReloadDataFromDb(false);
	}

	private async Task ReloadDataFromDb(bool forceReload = false)
	{
		using (await ObjectLock.GetSemaphore<CargoPartner>().UseWaitAsync())
		{
			if (CargoPartners == null) CargoPartners = new AcObservableCollection<CargoPartner>(await FruitBankSignalRClient.GetCargoPartners() ?? []);
			else if (CargoPartners.Count == 0 || forceReload)
			{
				CargoPartners.Replace(await FruitBankSignalRClient.GetCargoPartners() ?? []);
			}
		}

		CargoTrucks = CargoPartners.Where(x => x.CargoTrucks != null).SelectMany(x =>
		{
			if (x.CargoTrucks == null) return null;

			foreach (var cargoTruck in x.CargoTrucks) cargoTruck.CargoPartner = x;
			return x.CargoTrucks;
		}).ToList();

		if (!IsMasterGrid) return;

		using (await ObjectLock.GetSemaphore<Partner>().UseWaitAsync())
		{
			if (Partners == null) Partners = new AcObservableCollection<Partner>(await FruitBankSignalRClient.GetPartners() ?? []);
			else if (Partners.Count == 0 || forceReload)
			{
				Partners.Replace(await FruitBankSignalRClient.GetPartners() ?? []);
			}
		}

		if (Grid == null) return;

		using (await ObjectLock.GetSemaphore<Shipping>().UseWaitAsync())
			if (forceReload) await Grid.ReloadDataSourceAsync();

		if (forceReload) Grid.Reload();
	}

	async Task Grid_FocusedRowChanged(GridFocusedRowChangedEventArgs args)
	{
		if (Grid == null) return;

		if (Grid.IsEditing() && !Grid.IsEditingNewRow())
			await Grid.SaveChangesAsync();

		FocusedRowVisibleIndex = args.VisibleIndex;
		EditItemsEnabled = true;
	}

	async Task Grid_EditModelSaving(GridEditModelSavingEventArgs e)
	{
		var shipping = (Shipping)e.EditModel;   // a szerkesztett sor

		if (ValidateCargoConsistency(shipping, out var error)) return;

		e.Cancel = true;
		await DialogService.ShowMessageBoxAsync("Hibás adat", error!, MessageBoxRenderStyle.Danger);
		// e.IsNew → add vs update

		// ... before-save logika (validáció, számított mezők, CargoTrailer beállítás stb.)

		// megszakítás, ha kell:
		// e.Cancel = true;
	}

	async protected Task OnActiveTabChanged(int activeTabIndex)
	{
		_activeTabIndex = activeTabIndex;
		return;

		// switch (_activeTabIndex)
		// {
		// 	case 0:
		// 		if(ProductDtos == null)
		// 			ProductDtos = (await FruitBankSignalRClient.GetProductDtos() ?? []); //.Where(o => o.HasMeasuringAccess(LoggedInModel.CustomerDto?.Id, LoggedInModel.IsRevisor)).OrderBy(o => o.DateOfReceipt).ToList();
		// 		break;
		// 	case 1:
		// 		if(OrderDtos == null)
		// 			OrderDtos = (await FruitBankSignalRClient.GetAllOrderDtos() ?? []).OrderByDescending(o => o.Id).ToList(); //.Where(o => o.HasMeasuringAccess(LoggedInModel.CustomerDto?.Id, LoggedInModel.IsRevisor)).OrderBy(o => o.DateOfReceipt).ToList();
		// 		break;
		// 	case 2:
		// 		if (OrderItemDtos == null)
		// 			OrderItemDtos = (await FruitBankSignalRClient.GetAllOrderItemDtos() ?? []).OrderByDescending(o => o.Id).ToList(); //.Where(o => o.HasMeasuringAccess(LoggedInModel.CustomerDto?.Id, LoggedInModel.IsRevisor)).OrderBy(o => o.DateOfReceipt).ToList();
		// 		break;
		// }
	}

	private bool ValidateCargoConsistency(Shipping shipping, out string? error)
	{
		error = null;

		if (shipping.CargoTruckId != null)
		{
			var truck = CargoTrucks.FirstOrDefault(t => t.Id == shipping.CargoTruckId);
			if (truck == null || truck.CargoPartnerId != shipping.CargoPartnerId)
			{
				error = $"A vontató ({truck?.LicencePlate}) nem a kiválasztott fuvarozóhoz tartozik!";
				return false;
			}
		}

		if (shipping.CargoTrailerId == null) return true;

		var trailer = CargoTrucks.FirstOrDefault(t => t.Id == shipping.CargoTrailerId);
		if (trailer != null && trailer.CargoPartnerId == shipping.CargoPartnerId) return true;

		error = $"Az utánfutó ({trailer?.LicencePlate}) nem a kiválasztott fuvarozóhoz tartozik!";
		return false;
	}

}

