// 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 } from '@angular/core';
import { AlertController, ModalController } from '@ionic/angular';
import { CompaniesService } from 'src/app/providers/companies.service';
import { ConfigService } from 'src/app/providers/config.service';

@Component({
	selector: 'app-evento-appuntamento',
	templateUrl: './evento-appuntamento.component.html',
	styleUrls: ['./evento-appuntamento.component.scss'],
	standalone: false,
})
export class EventoAppuntamentoComponent implements OnInit {
	@Input() date!: any;
	@Input() tipo_utenza!: string;
	@Input() cmp_id!: number;
	title!: string;
	startDate!: string;
	endDate!: string;

	my_user: any = {};
	filter: any = {};
	lstCommesse: any[] = [];
	lstStati: any[] = [];

	slotText: string = '';
	durationText: string = '';

	constructor(
		private config: ConfigService,
		private modalController: ModalController,
		private companiesManager: CompaniesService,
		private alertController: AlertController
	) {}

	ngOnInit() {
		if (!this.date) {
			this.date = {};
			this.date.stato = {};
		} else {
			this.date.app_id = this.date.extendedProps.app_id;
			this.date.stato = this.date.extendedProps.stato;
			this.date.usr_id = this.date.extendedProps.usr_id;
			this.date.usr_displayname = this.date.extendedProps.usr_displayname;
			if (this.date.extendedProps.cmp_id) {
				this.cmp_id = this.date.extendedProps.cmp_id;
			}
			this.get_lstStatiAppuntamenti();
		}
		this.my_user = this.config.getUser();
		this.updateSlotTextAndDuration();
	}

	get_lstStatiAppuntamenti() {
		this.filter.pagina = 1;
		this.filter.righePagina = 100;
		this.filter.stato = -1;
		this.filter.cli_id = -1;
		this.companiesManager.get_lstAppointmentState().subscribe((res) => {
			if (res) {
				this.lstStati = res;
			}
		});
	}

	updateSlotTextAndDuration() {
		const start = new Date(this.date.start);
		const end = new Date(this.date.end);

		if (start && end) {
			const startTime = start.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
			const endTime = end.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

			this.slotText = `Slot: ${startTime} - ${endTime}`;
			const durationMinutes = Math.round((end.getTime() - start.getTime()) / (1000 * 60));
			this.durationText = `Durata: ${durationMinutes} minuti`;
		}
	}

	save() {
		if (this.date.app_id > 0) {
			this.companiesManager.updCompanyAppointment(this.cmp_id, this.date).subscribe((res: any) => {
				if (res > 0) {
					this.config.presentToastSuccess('Appuntamento aggiornato con successo!');
					this.close();
				}
			});
		} else {
			this.companiesManager.addCompanyAppointment(this.cmp_id, this.date).subscribe((res: any) => {
				if (res > 0) {
					this.config.presentToastSuccess('Appuntamento prenotato con successo!');
					this.close();
				}
			});
		}
	}

	async delete() {
        if (this.date.app_id > 0) {
            const alert = await this.alertController.create({
                header: 'Conferma Cancellazione',
                message: 'Sei sicuro di voler cancellare l\'appuntamento?',
                buttons: [
                    {
                        text: 'Annulla',
                        role: 'cancel'
                    },
                    {
                        text: 'Conferma',
                        handler: () => {
                            this.date.stato.id = 3;
                            this.companiesManager.updCompanyAppointment(this.cmp_id, this.date).subscribe((res: any) => {
                                if (res > 0) {
                                    this.config.presentToastSuccess('Appuntamento aggiornato con successo!');
                                    this.close();
                                }
                            });
                        }
                    }
                ]
            });

            await alert.present();
        } else {
            this.config.presentToastError("ID Appuntamento non valorizzato");
        }
    }

	close() {
		return this.modalController.dismiss(null, 'cancel');
	}
}
