// 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

// layout.service.ts
import { Injectable, signal, computed } from '@angular/core';

// Define the TabConfig interface
export interface TabConfig {
	icon: string;
	label: string;
	badge: number;
}

@Injectable({ providedIn: 'root' })
export class LayoutService {
	// Core signals for state management
	pageTitle = signal<string>('App');
	pageSubtitle = signal<string>('');
	backButtonHref = signal<string>('servizi');
	selectedTab = signal<string>('services');
	showBackButton = signal<boolean>(false);
	showTabBar = signal<boolean>(true);
	showHeader = signal<boolean>(true);
	headerRightButton = signal<{ icon: string; route: string } | null>(null);
	homeView = signal<'services' | 'categories'>('services');
	notificationCount = signal<number>(0);

	// Navigation history for breadcrumbs
	navigationHistory = signal<string[]>([]);

	// Tab configurations with badges
	tabConfigs = signal<Map<string, TabConfig>>(
		new Map([
			['bakeka', { icon: 'book', label: 'Bacheca', badge: 0 }],
			['services', { icon: 'pricetags', label: 'Servizi', badge: 0 }],
			['categories', { icon: 'grid', label: 'Categorie', badge: 0 }],
			['messaging', { icon: 'chatbubble-ellipses', label: 'Messaggi', badge: 0 }],
			['notifications', { icon: 'notifications', label: 'Notifiche', badge: 0 }],
			['profile', { icon: 'person', label: 'Profilo', badge: 0 }],
		]),
	);

	// Computed signals
	hasNotifications = computed(() => this.notificationCount() > 0);

	formattedTitle = computed(() => {
		const title = this.pageTitle();
		const count = this.notificationCount();
		return count > 0 ? `${title} (${count})` : title;
	});

	canGoBack = computed(() => this.navigationHistory().length > 1);

	breadcrumbs = computed(() => {
		const history = this.navigationHistory();
		return history.map((route) => ({
			label: this.getRouteLabel(route),
			path: route,
		}));
	});

	totalBadgeCount = computed(() => {
		const configs = this.tabConfigs();
		let total = 0;
		configs.forEach((config) => (total += config.badge));
		return total;
	});

	// Methods to update signals
	setPageConfig(config: { title?: string; subtitle?: string; tab?: string; showBack?: boolean; backButtonHref?: string; showHeader?: boolean; rightButton?: { icon: string; route: string } | null }) {
		if (config.title !== undefined) this.pageTitle.set(config.title);
		if ('subtitle' in config) this.pageSubtitle.set(config.subtitle ?? '');
		else if (config.title !== undefined) this.pageSubtitle.set('');
		if (config.tab !== undefined) this.selectedTab.set(config.tab);
		if (config.showBack !== undefined) this.showBackButton.set(config.showBack);
		if (config.backButtonHref !== undefined) this.backButtonHref.set(config.backButtonHref);
		if (config.showHeader !== undefined) this.showHeader.set(config.showHeader);
		if ('rightButton' in config) this.headerRightButton.set(config.rightButton ?? null);
	}

	// Notification management
	incrementNotifications() {
		this.notificationCount.update((count) => count + 1);
	}

	clearNotifications() {
		this.notificationCount.set(0);
	}

	setNotificationCount(count: number) {
		this.notificationCount.set(count);
	}

	// Tab badge management
	updateTabBadge(tab: string, count: number) {
		this.tabConfigs.update((configs) => {
			const newMap = new Map(configs);
			const config = newMap.get(tab);
			if (config) {
				config.badge = count;
			}
			return newMap;
		});
	}

	getTabBadge(tab: string): number {
		const configs = this.tabConfigs();
		const config = configs.get(tab);
		return config?.badge || 0;
	}

	// Navigation history management
	pushToHistory(route: string) {
		this.navigationHistory.update((history) => [...history, route]);
	}

	popFromHistory() {
		this.navigationHistory.update((history) => {
			const newHistory = [...history];
			newHistory.pop();
			return newHistory;
		});
	}

	clearHistory() {
		this.navigationHistory.set([]);
	}

	// Helper method to get route label
	getRouteLabel(route: string): string {
		// Extract the last segment of the route
		const segments = route.split('/').filter((s) => s);
		const lastSegment = segments[segments.length - 1] || 'home';

		// Capitalize and format the label
		return lastSegment.replace(/-/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
	}

	// Reset all state
	resetState() {
		this.pageTitle.set('App');
		this.pageSubtitle.set('');
		this.selectedTab.set('services');
		this.homeView.set('services');
		this.showBackButton.set(false);
		this.showTabBar.set(true);
		this.notificationCount.set(0);
		this.navigationHistory.set([]);

		// Reset all tab badges
		this.tabConfigs.update((configs) => {
			const newMap = new Map(configs);
			newMap.forEach((config) => (config.badge = 0));
			return newMap;
		});
	}
}
