// 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 { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '../../../providers/config.service';
import { LayoutService } from '../../../providers/layout.service';
import { AssembleeService } from '../../../providers/assemblee.service';
import { FunctionService } from '../../../providers/function.service';
import { Assemblea } from '../../../models/assemblea.model';

type Segment = 'programmate' | 'concluse' | 'tutte';

@Component({
	selector: 'app-assemblee-list',
	templateUrl: './assemblee-list.page.html',
	styleUrls: ['./assemblee-list.page.scss'],
	standalone: false,
})
export class AssembleeListPage {
	cmp_id = 0;
	prt_id = 0;
	// permessi via funzioni di modulo (ruolo), non più hardcoded sul cliente
	moduleName = 'Assemblee';
	canCreate = false;
	canManage = false;
	loading = false;

	filtered: Assemblea[] = [];
	segment: Segment = 'programmate';
	search = '';
	private searchTimer: any;

	constructor(
		private route: ActivatedRoute,
		private router: Router,
		private config: ConfigService,
		public layout: LayoutService,
		private service: AssembleeService,
		private funService: FunctionService,
	) {}

	ionViewWillEnter() {
		this.resolveIds();
		this.layout.setPageConfig({ title: 'Assemblee', showBack: true, backButtonHref: '/servizi' });
		this.funService.funzionibyuser(this.moduleName).subscribe((res: any[]) => {
			const funcs = (res || []).map((f) => f.mdfu_function);
			this.canCreate = funcs.includes('add');
			this.canManage = funcs.includes('add') || funcs.includes('modifica') || funcs.includes('delete');
		});
		this.load();
	}

	private resolveIds() {
		let r: ActivatedRoute | null = this.route;
		while (r) {
			const pm = r.snapshot.paramMap;
			if (pm.get('cmp_id')) this.cmp_id = +(pm.get('cmp_id') as string);
			if (pm.get('prt_id')) this.prt_id = +(pm.get('prt_id') as string);
			r = r.parent;
		}
	}

	load(ev?: any) {
		this.loading = true;
		// ricerca testuale + filtro stato entrambi server-side (lo stato è derivato dal segment selezionato)
		this.service.getAssemblee(this.cmp_id, this.search || '', 'asm_first_call_dt DESC', 100, 1, this.statusFilter()).subscribe({
			next: (rows) => {
				this.filtered = rows || [];
				this.loading = false;
				ev?.target?.complete();
			},
			error: (e) => {
				this.config.presentToastError(typeof e === 'string' ? e : 'Errore nel caricamento delle assemblee');
				this.loading = false;
				ev?.target?.complete();
			},
		});
	}

	// cambio tab stato: ricarica dal backend con il nuovo filtro stato
	onSegment() {
		this.load();
	}

	// ricerca testuale lato backend, con piccolo debounce per non chiamare l'endpoint a ogni tasto
	onSearch() {
		clearTimeout(this.searchTimer);
		this.searchTimer = setTimeout(() => this.load(), 350);
	}

	// segment → valore i_status per il backend ('' = tutte)
	private statusFilter(): string {
		if (this.segment === 'programmate') return 'programmata';
		if (this.segment === 'concluse') return 'conclusa,annullata';
		return '';
	}

	// ─── UI helpers ───────────────────────────────────────────────
	statusColor(a: Assemblea): string {
		if (a.asm_status === 'annullata') return 'danger';
		if (a.asm_status === 'conclusa') return 'success';
		return this.isPassata(a) ? 'medium' : 'warning';
	}

	statusLabel(a: Assemblea): string {
		if (a.asm_status === 'annullata') return 'Annullata';
		if (a.asm_status === 'conclusa') return 'Conclusa';
		return this.isPassata(a) ? 'Passata' : 'Programmata';
	}

	tipoColor(a: Assemblea): string {
		return a.asm_type === 'straordinaria' ? 'tertiary' : 'primary';
	}

	tipoLabel(a: Assemblea): string {
		return a.asm_type === 'straordinaria' ? 'Straordinaria' : 'Ordinaria';
	}

	isPassata(a: Assemblea): boolean {
		const dt = a.asm_second_call_dt || a.asm_first_call_dt;
		return dt ? new Date(dt) < new Date() : false;
	}

	// ─── navigation ───────────────────────────────────────────────
	private base(): string {
		return `/portale/${this.prt_id}/company/${this.cmp_id}/service/assemblee`;
	}

	openDetail(a: Assemblea) {
		this.router.navigate([this.base(), 'detail', a.asm_id]);
	}

	nuova() {
		this.router.navigate([this.base(), 'add']);
	}

	goCalendar() {
		this.router.navigate([this.base(), 'calendar']);
	}
}
