// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { DatePipe } from '@angular/common';
import { AfterViewInit, Component, EventEmitter, Input, OnChanges, OnInit, Output, QueryList, SimpleChanges, ViewChildren } from '@angular/core';
import { CalendarComponent } from '../calendar/calendar.component';
import { SuggestionSimpleInputComponent } from '../suggestion-input/suggestion-simple-input.component';

@Component({
	selector: 'app-campi-form',
	templateUrl: 'campi_form.component.html',
	styleUrls: ['campi_form.component.scss'],
	standalone: false,
})
export class CampiFormComponent implements OnInit, OnChanges, AfterViewInit {
	@Input() form: any;
	@Input() folder_id: number = -1;
	@Input() form_id: number = -1;
	@Input() view = false;
	/*@Input() search_sottocartelle = false;*/
	@Input() mode_search = false;
	@Input() start_search = false;
	@Input() start_reset = false;
	@Input() start_salva = false;
	@Input() tipo_visualizzazione!: string;
	@Output() emitAll = new EventEmitter();
	@Output() emitReset = new EventEmitter();

	campi: any = {};
	view_filter = true;

	// Output separato per aggiornamenti valore immediati (type=15, ecc.)
	@Output() emitValue = new EventEmitter();

	@ViewChildren('field_suggsimple') _field_suggsimple!: QueryList<SuggestionSimpleInputComponent>;
	@ViewChildren('field_calendar') _field_calendar!: QueryList<CalendarComponent>;
	//@ViewChildren('field_select') _field_select!: QueryList<IonSelect>;

	modena_list: string[] = [];
	lst_tabindex: number[] = [];

	associazioni_precompilazione: any[] = [];

	/* Gestione Geolocalizzazione*/
	imageBase64 = '';
	modena_lst_mappali: any[] = [];

	constructor(public datePipe: DatePipe) {}

	ngOnInit() {
		this.sortCampiByOrder();
	}

	sortCampiByOrder() {
		if (this.campi && Array.isArray(this.campi)) {
			const geoItems = this.campi.filter((item) => item.group_label === 'geolocalizzazione');
			const otherItems = this.campi.filter((item) => item.group_label !== 'geolocalizzazione');

			geoItems.sort((a, b) => a.row - b.row);

			otherItems.sort((a, b) => {
				if (a.row !== b.row) {
					return a.row - b.row;
				}
				return a.column - b.column;
			});

			if (geoItems.length === 0) {
				this.campi = otherItems;
				return;
			}

			const minGeoRow = geoItems[0].row;

			let insertionIndex = 0;
			while (insertionIndex < otherItems.length && otherItems[insertionIndex].row < minGeoRow) {
				insertionIndex++;
			}

			const result = [...otherItems.slice(0, insertionIndex), ...geoItems, ...otherItems.slice(insertionIndex)];

			this.campi = result;
		}
	}

	ngOnChanges(changes: SimpleChanges) {
		if (changes['form']) {
			this.campi = changes['form'].currentValue;
			this.loadCampi();
			this.sortCampiByOrder();
		}
		if (changes['start_search'] && !changes['start_search'].firstChange) {
			if (this.start_search) {
				this.emitAll.emit({ campi: this.campi });
			}
		}
		if (changes['start_salva'] && !changes['start_salva'].firstChange) {
			if (this.start_salva) {
				this.emitAll.emit({ campi: this.campi });
			}
		}
		if (changes['start_reset']) {
			if (this.start_reset) {
				this.reset();
				this.emitReset.emit({ campi: this.campi });
			}
		}
	}

	ngAfterViewInit() {
		if (this.tipo_visualizzazione == 'form_file') {
			setTimeout(() => {
				let firstSuggSimple = null;
				if (this._field_suggsimple) {
					const elements = this._field_suggsimple
						.toArray()
						.filter((field) => field.tabindex >= 0)
						.sort((a, b) => a.tabindex - b.tabindex);
					if (elements[0]) {
						firstSuggSimple = elements[0];
						//elements[0].setFocus();
					}
				}

				let firstCalendar = null;
				if (this._field_calendar) {
					const elements = this._field_calendar
						.toArray()
						.filter((field) => field.tabindex >= 0)
						.sort((a, b) => a.tabindex - b.tabindex);
					if (elements[0]) {
						firstCalendar = elements[0];
						//elements[0].setFocus();
					}
				}

				if (firstSuggSimple && firstCalendar) {
					if (firstSuggSimple.tabindex < firstCalendar.tabindex) {
						firstSuggSimple.setFocus();
					} else {
						firstCalendar.setFocus();
					}
				} else if (firstSuggSimple) {
					firstSuggSimple.setFocus();
				} else if (firstCalendar) {
					firstCalendar.setFocus();
				}
			}, 500);
		}
	}

	loadCampi() {
		if (this.campi) {
			if (!this.view && this.tipo_visualizzazione != 'form_file') {
				this.reset();
			} else {
				this.sortCampiByOrder();

				let tab_index = 0;
				this.lst_tabindex = [];
				this.modena_list = [];

				this.campi.forEach((element: any) => {
					element.search = 0;

					if (!element.disabled) {
						this.lst_tabindex.push(tab_index);
						tab_index++;
					} else {
						this.lst_tabindex.push(-1);
					}
				});

				if (this.tipo_visualizzazione == 'info_metadata') {
					this.campi.forEach((el: any) => {
						el.disabled = true;
					});
				}

				if (this.tipo_visualizzazione == 'form_file') {
					this.ngAfterViewInit();
				}
			}
		}
	}

	reset() {
		this.campi.forEach((el: any) => {
			el.value = undefined;
			el.value_da = undefined;
			el.value_a = undefined;
		});
	}

	onDateChange(newDate: Date | null, campo: any) {
		campo.value = newDate ? this.datePipe.transform(newDate, 'yyyy-MM-dd') : '';
	}

	onDateChangeDa(newDate: Date | null, campo: any) {
		campo.value_da = newDate ? this.datePipe.transform(newDate, 'yyyy-MM-dd') : '';
	}

	onDateChangeA(newDate: Date | null, campo: any) {
		campo.value_a = newDate ? this.datePipe.transform(newDate, 'yyyy-MM-dd') : '';
	}

	getSuggestion(c: any): string[] {
		if (c.name === 'via_da_elenco') {
			return this.modena_list;
		} else if (c.type == 3) {
			return c.option.map((opt: any) => `${opt.value}|${opt.text}`);
		}

		let files = JSON.parse(localStorage.getItem('storico_campi') || '[]');

		const datiCounts: { [key: string]: number } = {};
		files.forEach((item: any) => {
			const valCampo = item.fields.find((field: any) => field.name === c.name)?.value;
			if (valCampo) {
				if (datiCounts[valCampo]) {
					datiCounts[valCampo]++;
				} else {
					datiCounts[valCampo] = 1;
				}
			}
		});

		const filteredCounts = Object.entries(datiCounts)
			.filter(([key, count]: [string, number]) => count >= 3)
			.map(([key]) => key);

		return filteredCounts;
	}

	getValueCombo(campo: any): string {
		let res = '';
		if (campo.value) {
			let opt = campo.option.find((x: any) => x.value == campo.value);
			if (opt) {
				res = opt.text;
			}
		}
		return res;
	}

	onSuggestionSimpleSelected(obj: any, campo: any): void {
		if (!obj && !obj.value) {
			obj = {};
			obj.value = '';
			obj.isOnBlur = false;
		}

		campo.value = obj.value;
	}

	// === Attività (type=15) — mirror del portale per rapportino dipendente ===
	initActivityValue(campo: any): boolean {
		if (!campo.value || typeof campo.value !== 'object' || Array.isArray(campo.value)) {
			campo.value = { presente: true, attivita: [], note: '', ore_ordinarie: 0, ore_straordinarie: 0 };
		}
		if (!Array.isArray(campo.value.attivita)) campo.value.attivita = [];
		if (typeof campo.value.presente !== 'boolean') campo.value.presente = true;
		if (typeof campo.value.note !== 'string') campo.value.note = '';
		return true;
	}

	addActivityRow(campo: any) {
		this.initActivityValue(campo);
		campo.value.attivita.push({ descrizione: '', durata: 0 });
		this.emitValue.emit({ campi: this.campi });
	}

	removeActivityRow(campo: any, index: number) {
		campo.value.attivita.splice(index, 1);
		this.emitValue.emit({ campi: this.campi });
	}

	getTotalOreAttivita(campo: any): number {
		if (!campo?.value?.attivita) return 0;
		return campo.value.attivita.reduce((sum: number, a: any) => sum + (+a.durata || 0), 0);
	}

	onActivityValueChange() {
		this.emitValue.emit({ campi: this.campi });
	}
}
