// 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, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertController, LoadingController } from '@ionic/angular';

import { ConfigService } from 'src/app/providers/config.service';
import { BizServiceTypesService } from 'src/app/providers/biz-service-types.service';
import { BizServiceCategoriesService } from 'src/app/providers/biz-service-categories.service';
import { ServiceType, ServiceTypeModeOptions } from 'src/models/biz-appointments/service-type.model';
import { ServiceCategory } from 'src/models/biz-appointments/service-category.model';

@Component({
	standalone: false,
	selector: 'app-biz-service-types',
	templateUrl: './biz-service-types.page.html',
	styleUrls: ['./biz-service-types.page.scss'],
})
export class BizServiceTypesPage implements OnInit {
	serviceTypes: ServiceType[] = [];
	categories: ServiceCategory[] = [];
	loading: boolean = false;
	cmp_id: number = 0;
	modeOptions = ServiceTypeModeOptions;

	// Modal tipo servizio
	showFormModal: boolean = false;
	isNew: boolean = true;
	formData: Partial<ServiceType> = {};

	// Modal nuova categoria
	showCategoryModal: boolean = false;
	newCategoryName: string = '';

	constructor(
		private route: ActivatedRoute,
		private alertController: AlertController,
		private loadingController: LoadingController,
		private configService: ConfigService,
		private serviceTypesService: BizServiceTypesService,
		private categoriesService: BizServiceCategoriesService,
	) {}

	ngOnInit(): void {
		this.cmp_id = Number(this.route.snapshot.paramMap.get('cmp_id') || this.route.parent?.snapshot.paramMap.get('cmp_id') || 0);
		this.loadList();
		this.loadCategories();
	}

	loadCategories(): void {
		this.categoriesService.getServiceCategories(this.cmp_id).subscribe({
			next: (data: any) => {
				this.categories = data || [];
			},
		});
	}

	openNewCategory(): void {
		this.newCategoryName = '';
		this.showCategoryModal = true;
	}

	saveNewCategory(): void {
		if (!this.newCategoryName.trim()) {
			this.configService.presentToastError('Inserire il nome della categoria');
			return;
		}
		this.categoriesService.getServiceCategories(this.cmp_id); // just to have type
		const cat: Partial<ServiceCategory> = {
			sc_cmp_id: this.cmp_id,
			sc_name: this.newCategoryName.trim(),
			sc_color: '#6366F1',
			sc_order: 0,
		};

		// Use the HTTP call directly
		this.categoriesService.insertServiceCategory(cat).subscribe({
			next: (newId: number) => {
				this.configService.presentToastSuccess('Categoria creata');
				this.showCategoryModal = false;
				this.loadCategories();
				this.formData.st_category_id = newId;
			},
			error: () => {
				this.configService.presentToastError('Errore creazione categoria');
			},
		});
	}

	getCategoryName(id: number | undefined): string {
		if (!id) return '-';
		const cat = this.categories.find((c) => c.sc_id === id);
		return cat ? cat.sc_name : '-';
	}

	async loadList(): Promise<void> {
		this.loading = true;
		this.serviceTypesService.getServiceTypes(this.cmp_id).subscribe({
			next: (data: any) => {
				this.serviceTypes = data || [];
			},
			error: () => {
				this.configService.presentToastError('Errore caricamento tipi servizio');
			},
			complete: () => {
				this.loading = false;
			},
		});
	}

	openNew(): void {
		this.isNew = true;
		this.formData = {
			st_cmp_id: this.cmp_id,
			st_name: '',
			st_description: '',
			st_mode: 'SLOT_FISSO',
			st_duration_minutes: 30,
			st_color: '#6366F1',
			st_requires_attachments: false,
			st_active: true,
			st_order: 0,
		};
		this.showFormModal = true;
	}

	openEdit(st: ServiceType): void {
		this.isNew = false;
		this.formData = { ...st };
		this.showFormModal = true;
	}

	async save(): Promise<void> {
		if (!this.formData.st_name?.trim()) {
			this.configService.presentToastError('Il nome è obbligatorio');
			return;
		}

		const loader = await this.loadingController.create({ message: 'Salvataggio...' });
		await loader.present();

		const obs = this.isNew ? this.serviceTypesService.insertServiceType(this.formData) : this.serviceTypesService.updateServiceType(this.formData as ServiceType);

		obs.subscribe({
			next: () => {
				this.configService.presentToastSuccess(this.isNew ? 'Tipo servizio creato' : 'Tipo servizio aggiornato');
				this.showFormModal = false;
				this.loadList();
			},
			error: () => {
				this.configService.presentToastError('Errore salvataggio');
			},
			complete: () => {
				loader.dismiss();
			},
		});
	}

	async confirmDelete(st: ServiceType): Promise<void> {
		const alert = await this.alertController.create({
			header: 'Elimina tipo servizio',
			message: `Eliminare "${st.st_name}"?`,
			buttons: [
				{ text: 'Annulla', role: 'cancel' },
				{
					text: 'Elimina',
					role: 'destructive',
					handler: () => this.deleteServiceType(st),
				},
			],
		});
		await alert.present();
	}

	private deleteServiceType(st: ServiceType): void {
		this.serviceTypesService.deleteServiceType(st.st_id).subscribe({
			next: () => {
				this.configService.presentToastSuccess('Tipo servizio eliminato');
				this.loadList();
			},
			error: () => {
				this.configService.presentToastError('Errore eliminazione');
			},
		});
	}

	getModeLabel(mode: string): string {
		const opt = this.modeOptions.find((o) => o.value === mode);
		return opt ? opt.label : mode;
	}
}
