// 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, Input, OnInit, OnDestroy } from '@angular/core';
import { ConfigService } from 'src/app/providers/config.service';

import { HttpClient } from '@angular/common/http';
import { AlertController, IonicModule, ModalController, PopoverController } from '@ionic/angular';
import { Router } from '@angular/router';
import { UserMenuComponent } from '../user-menu/user-menu.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Subscription } from 'rxjs';
import { GeolocationService, GeoPermissionStatus } from 'src/app/providers/geolocation.service';

@Component({
	selector: 'app-header',
	templateUrl: './header.component.html',
	styleUrls: ['./header.component.scss'],
	imports: [FormsModule, IonicModule, ReactiveFormsModule],
})
export class HeaderComponent implements OnInit, OnDestroy {
	@Input() nome_sezione = 'Dashboard';
	@Input() view_btn_back = false;
	@Input() showUserInfo = false;

	unreadCount = 0;
	private unreadInterval: any;

	geoStatus: GeoPermissionStatus = 'idle';
	private geoSub?: Subscription;

	constructor(private popoverController: PopoverController, private modalController: ModalController, private alertController: AlertController, private router: Router, public config: ConfigService, private http: HttpClient, public geoService: GeolocationService) {}

	ngOnInit() {
		if (this.config.isLogged()) {
			this.loadUnreadCount();
			this.unreadInterval = setInterval(() => this.loadUnreadCount(), 60000);
		}
		this.geoSub = this.geoService.status$.subscribe((s) => (this.geoStatus = s));
	}

	ngOnDestroy() {
		if (this.unreadInterval) {
			clearInterval(this.unreadInterval);
		}
		this.geoSub?.unsubscribe();
	}

	get geoIcon(): string {
		return this.geoStatus === 'granted' ? 'location' : 'location-outline';
	}

	get geoColor(): string {
		switch (this.geoStatus) {
			case 'granted':
				return 'success';
			case 'denied':
				return 'medium';
			case 'loading':
				return 'warning';
			default:
				return 'light';
		}
	}

	get geoTitle(): string {
		switch (this.geoStatus) {
			case 'granted':
				return 'Posizione attiva';
			case 'denied':
				return 'Posizione non disponibile';
			case 'loading':
				return 'Recupero posizione...';
			default:
				return 'Abilita posizione';
		}
	}

	onGeoClick() {
		if (this.geoStatus === 'loading') return;
		if (this.geoStatus === 'denied') {
			this.geoService.openSystemLocationSettings();
			return;
		}
		this.geoService.requestPosition().catch(() => {});
	}

	loadUnreadCount() {
		/*this.http.get(this.config.serviceUrl_PortalManager + 'notify/unread-count').subscribe({
			next: (count: any) => (this.unreadCount = count),
			error: () => {},
		});*/
	}

	goToNotifications() {
		this.router.navigate(['/notifications']);
	}

	getUserInitials(): string {
		return this.config.getUsernameInitials();
	}

	getUserFullName(): string {
		const user = this.config.getUser();
		return user ? `${user.usr_firstname} ${user.usr_lastname}` : '';
	}

	getUserRole(): string {
		// Return user's primary role or department
		return this.config.getUser()?.usr_role || 'User';
	}

	getAvatarColor(): string {
		return this.config.getColorFromDisplayName();
	}

	getUserAvatar(): string {
		return this.config.getUserAvatar();
	}

	goBack() {
		window.history.back();
	}

	async presentUserMenu(event: any) {
		const popover = await this.popoverController.create({
			component: UserMenuComponent,
			event: event,
			translucent: true,
			cssClass: 'user-menu-popover-wrapper',
		});

		await popover.present();
	}

	login() {
		this.router.navigate(['/login']);
	}
}
