@using AyCode.Blazor.Components.Components.Grids
@using AyCode.Utils.Extensions
@using FruitBank.Common.Dtos
@using FruitBank.Common.Entities
@* @using FruitBankHybrid.Shared.Components.FileUploads *@
@using FruitBankHybrid.Shared.Components.Grids.ShippingDocuments
@using FruitBankHybrid.Shared.Databases
@using FruitBankHybrid.Shared.Services.SignalRs
@using System.Text
@using AyCode.Core.Extensions
@using AyCode.Core.Helpers
@using AyCode.Core.Interfaces
@using AyCode.Core.Loggers
@using FruitBank.Common
@using FruitBank.Common.Enums
@using FruitBank.Common.Models
@using FruitBankHybrid.Shared.Services.Loggers

@inject IEnumerable<IAcLogWriterClientBase> LogWriters
@inject FruitBankSignalRClient FruitBankSignalRClient

<MgGridWithInfoPanel ShowInfoPanel="@IsMasterGrid">
	<GridContent>
		<GridShippingDocumentBase @ref="Grid" CssClass="@GridCss" DataSource="@ShippingDocuments" SignalRClient="FruitBankSignalRClient" AutoSaveLayoutName="GridShippingDocument"
								  ParentDataItem="@ParentDataItem" Logger="_logger" ValidationEnabled="false" EditMode="GridEditMode.EditRow" OnGridFocusedRowChanged="Grid_FocusedRowChanged">
			<Columns>
				<MgGridDataColumn FieldName="Id" SortIndex="0" SortOrder="GridColumnSortOrder.Descending" ReadOnly="true"/>
				<DxGridDataColumn FieldName="PartnerId" Caption="Partner" Visible="@(!ParentDataItemIsPartner)" ReadOnly="@ParentDataItemIsPartner">
					<EditSettings>
						<DxComboBoxSettings Data="Partners"
											ValueFieldName="Id"
											TextFieldName="Name"
											DropDownBodyCssClass="dd-body-class"
											ListRenderMode="ListRenderMode.Entire"
											SearchMode="ListSearchMode.AutoSearch"
											SearchFilterCondition="ListSearchFilterCondition.Contains"
											ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto">
							<Columns>
								<DxListEditorColumn FieldName="@nameof(Partner.Id)" />
								<DxListEditorColumn FieldName="@nameof(Partner.Name)" />
								<DxListEditorColumn FieldName="@nameof(Partner.TaxId)" />
							</Columns>
						</DxComboBoxSettings>
					</EditSettings>
				</DxGridDataColumn>
				<DxGridDataColumn FieldName="Shipping.ShippingDate" Caption="Beérkezés" ReadOnly="true" />
				<DxGridDataColumn FieldName="ShippingId" Caption="Shipping" Visible="@(!ParentDataItemIsShipping)" ReadOnly="@ParentDataItemIsShipping">
					<EditSettings>
						<DxComboBoxSettings Data="Shippings"
											ValueFieldName="Id"
											TextFieldName="LicencePlate"
											DropDownBodyCssClass="dd-body-class"
											ListRenderMode="ListRenderMode.Entire"
											SearchMode="ListSearchMode.AutoSearch"
											SearchFilterCondition="ListSearchFilterCondition.Contains"
											ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto">
							<Columns>
								<DxListEditorColumn FieldName="@nameof(Shipping.Id)" />
								<DxListEditorColumn FieldName="@nameof(Shipping.ShippingDate)" />
								<DxListEditorColumn FieldName="@nameof(Shipping.LicencePlate)" />
								<DxListEditorColumn FieldName="@nameof(Shipping.Comment)" />
								<DxListEditorColumn FieldName="@nameof(Shipping.CargoCompany)" />
							</Columns>
						</DxComboBoxSettings>
					</EditSettings>
				</DxGridDataColumn>

				<DxGridDataColumn FieldName="DocumentIdNumber" />
				<DxGridDataColumn FieldName="ShippingDate" Caption="LoadDate" />
				<DxGridDataColumn FieldName="Country" />

				<DxGridDataColumn FieldName="TotalPallets" />
				<DxGridDataColumn FieldName="IsAllMeasured" ReadOnly="true" />
				<DxGridDataColumn FieldName="Comment" />
				<DxGridDataColumn FieldName="PdfFileName" />
				<DxGridDataColumn FieldName="Created" ReadOnly="true" />
				<DxGridDataColumn FieldName="Modified" ReadOnly="true" />
				<DxGridCommandColumn Visible="@(!IsMasterGrid)" Width="120"/>
			</Columns>
			<DetailRowTemplate>
				@if (IsMasterGrid)
				{
					var shippingDocument = ((ShippingDocument)context.DataItem);

					<DxTabs ActiveTabIndexChanged="(i) => OnActiveTabChanged(i)">
						<DxTabPage Text="Szállítmány tételek">
							@{
								var observableShippingItem = new AcObservableCollection<ShippingItem>(shippingDocument?.ShippingItems ?? []);
								<GridShippingItemTemplate ShippingItems="@observableShippingItem" ParentDataItem="@shippingDocument" />
							}
						</DxTabPage>
						<DxTabPage Text="Mérések">
							@{
								var shippingItemPallets = shippingDocument?.ShippingItems?.SelectMany(oi => oi.ShippingItemPallets ?? []).ToList() ?? [];
								<GridShippingItemPallets ShippingItemPallets="@shippingItemPallets" IsMasterGrid="false" />
							}
						</DxTabPage>

					</DxTabs>
				}
			</DetailRowTemplate>
			<ToolbarTemplate>
				@if (IsMasterGrid)
				{
					<MgGridToolbarTemplate @ref="toolbar" Grid="Grid" OnReloadDataClick="() => ReloadDataFromDb(true)">
						<ToolbarItemsExtended>
@* 							<DxToolbarItem BeginGroup="true">
								<Template Context="ctxToolbarItemFileUpload">
									<FileUpload OnFileUploaded="OnFileUploaded"></FileUpload>
								</Template>
							</DxToolbarItem>
 *@							
							<DxToolbarItem BeginGroup="true" Text="Ai process..." IconCssClass="grid-ai" Click="Callback" Enabled="@(!windowVisible)">
							</DxToolbarItem>

						</ToolbarItemsExtended>
					</MgGridToolbarTemplate>
				}
			</ToolbarTemplate>
			<GroupSummary>
				<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
								   FieldName="Quantity"
								   FooterColumnName="Quantity" />
				<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
								   FieldName="NetWeight"
								   FooterColumnName="NetWeight" />
				<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
								   FieldName="PriceInclTax"
								   FooterColumnName="PriceInclTax" />
			</GroupSummary>
		</GridShippingDocumentBase>
	</GridContent>
	<ChildContent>
		<GridShippingDocumentInfoPanel />
	</ChildContent>
</MgGridWithInfoPanel>

<DxWindow @ref=windowRef
          AllowResize="true"
          ShowCloseButton="true"
		  CloseOnEscape="true"
		  ShowHeader="true"
		  HeaderText="Ai process..."
          ShowFooter="false"
          SizeMode="SizeMode.Large"
		  Width="95vw"
          Height="95vh"
		  Closing="Callback2"
		  @bind-Visible=windowVisible>
@* 	<HeaderTemplate Context="dfgsdf">
		<DxButton CssClass="popup-button my-1 ms-2" RenderStyle="ButtonRenderStyle.Primary" Text="Bezár" Click="@dfgsdf.CloseCallback" />
	</HeaderTemplate>
 *@	<BodyContentTemplate Context="ctxAiProcessBody">
		<AiProcessFormTemplate />
	</BodyContentTemplate>
</DxWindow>
@code {
	[Inject] public required DatabaseClient Database { get; set; }
	[Inject] public required LoggedInModel LoggedInModel { get; set; }

	[Parameter] public AcObservableCollection<Shipping>? Shippings { get; set; }
	[Parameter] public AcObservableCollection<Partner>? Partners { get; set; }
	[Parameter] public AcObservableCollection<ShippingDocument>? ShippingDocuments { get; set; }

	[Parameter] public Func<List<Partner>?, Task>? OnUploadedFileParsed { get; set; }
	[Parameter] public IId<int>? ParentDataItem { get; set; }

	public bool IsMasterGrid => ParentDataItem == null;
	public bool ParentDataItemIsShipping => (ParentDataItem is Shipping);
	public bool ParentDataItemIsPartner => (ParentDataItem is Partner);
	string GridCss => !IsMasterGrid ? "hide-toolbar" : string.Empty;

	MgGridToolbarTemplate toolbar;
	const string ExportFileName = "ExportResult";
	string _localStorageKey = "GridShippingDocument_";

	string GridSearchText = "";
	bool EditItemsEnabled { get; set; } = true;
	int FocusedRowVisibleIndex { get; set; }

	private DxWindow windowRef;
	private bool windowVisible;

	public GridShippingDocumentBase Grid { get; set; }
	private LoggerClient<GridShippingDocument> _logger = null!;
	private int _activeTabIndex;

	protected override async Task OnInitializedAsync()
	{
		_logger = new LoggerClient<GridShippingDocument>(LogWriters.ToArray());

		_localStorageKey += LoggedInModel.CustomerDto!.Id;
		await ReloadDataFromDb();
	}

	private async Task ReloadDataFromDb(bool forceReload = false)
	{
		if (!ParentDataItemIsPartner)
		{
			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 (!ParentDataItemIsShipping)
		{
			using (await ObjectLock.GetSemaphore<Shipping>().UseWaitAsync())
			{
				if (Shippings == null) Shippings = new AcObservableCollection<Shipping>(await FruitBankSignalRClient.GetShippings() ?? []);
				else if (Shippings.Count == 0 || forceReload)
				{
					Shippings.Replace(await FruitBankSignalRClient.GetShippings() ?? []);
				}
			}
		}

		if (!IsMasterGrid)
		{
			if (Shippings == null && ParentDataItem is Shipping shippingParent) Shippings = [shippingParent];
			if (Partners == null && ParentDataItem is Partner partnerParent) Partners = [partnerParent];
			return;
		}

		if (Grid == null) return;

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

		if (forceReload) Grid.Reload();
	}

	private async Task OnFileUploaded(byte[] arg)
	{
		var utfString = Encoding.UTF8.GetString(arg, 0, arg.Length);
		var result = await FruitBankSignalRClient.ProcessAndSaveFullShippingJson(utfString, LoggedInModel.CustomerDto!.Id);

		if (result != null)
		{
			foreach (var shippingDocument in result.SelectMany(partner => partner.ShippingDocuments ?? []))
			{
				ShippingDocuments!.Add(shippingDocument);
			}
		}

		Grid.Reload();

		if (OnUploadedFileParsed != null)
			await OnUploadedFileParsed(result);
	}

	async Task Grid_FocusedRowChanged(GridFocusedRowChangedEventArgs args)
	{
		if (Grid != null && Grid.IsEditing() && !Grid.IsEditingNewRow())
			await Grid.SaveChangesAsync();

		if (toolbar != null)
		{
			var shippingDocument = (args.DataItem as ShippingDocument)!;
			toolbar.EnableDelete = shippingDocument.ShippingItems?.All(x => x.MeasuringStatus == MeasuringStatus.NotStarted) ?? true;
		}

		FocusedRowVisibleIndex = args.VisibleIndex;
		EditItemsEnabled = true;
	}

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

	private async Task Callback(ToolbarItemClickEventArgs obj)
	{
		if (windowVisible) await windowRef.CloseAsync();
		else await windowRef.ShowAsync();
	}

	private void Callback2(WindowClosingEventArgs obj)
	{
		ReloadDataFromDb(true).Forget(_logger);
	}

}
