import { Component, ChangeDetectorRef } from '@angular/core';
import { ModalController, MenuController, NavController } from '@ionic/angular';
import { EventService } from '../../../services/event.service';
import { EnvService } from 'src/app/services/env.service';
import { AuthService } from 'src/app/services/auth.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { TranslateService } from '@ngx-translate/core';
import { LanguageService } from 'src/app/services/language.service';
import { AlertService } from 'src/app/services/alert.service';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-contracted',
  templateUrl: './contracted.page.html',
  styleUrls: ['./contracted.page.scss'],
  standalone: false
})
export class ContractedPage {

  ccontracts: any[] = [];
  ccontracts_dates: any[] = [];
  lang: boolean = false;
  loading = true;

  constructor(
    private modalController: ModalController,
    private menu: MenuController,
    private navCtrl: NavController,
    private events: EventService,
    private alertController: AlertController,
    private authService: AuthService,
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private translateService: TranslateService,
    private languageService: LanguageService,
    private env: EnvService,
    private cdr: ChangeDetectorRef,
  ) {
    this.events.subscribe('refreshccontracts', (data) => {
      this.getccontracts();
    });
  }

  ionViewWillEnter() {
    this.lang = this.languageService.getDefaultLanguage() === 'es';
    this.loading = true;
    this.getccontracts();
  }

  refresh(event: any) {
    this.ichambaService.getCurrentcontracts().subscribe(
      data => {
        this.ccontracts = data;
        this.ccontracts_dates = [];
        for (var i of this.ccontracts) {
          const locale = this.lang ? 'es-US' : 'en-US';
          this.ccontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace(',', '')).toLocaleDateString(locale, { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'long' }));
        }
        this.cdr.detectChanges();
        event.target.complete();
      }, error => {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
        event.target.complete();
      });
  }

  getccontracts() {
    this.ichambaService.getCurrentcontracts().subscribe(
      data => {
        this.ccontracts = data;
        this.ccontracts_dates = [];
        for (var i of this.ccontracts) {
          const locale = this.lang ? 'es-US' : 'en-US';
          this.ccontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace(',', '')).toLocaleDateString(locale, { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'long' }));
        }
        this.loading = false;
        this.cdr.detectChanges();
      }, error => {
        this.loading = false;
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
      });
  }

  cancelContract(id: String, date: string) {
    let current_date = new Date().toISOString();
    let selected_date = new Date(date).toISOString();
    let differenceDate = (Number(new Date(selected_date)) - Number(new Date(current_date)));

    /* if (differenceDate < 86400000) {
      this.presentAlert(id)
    } else { */
    this.ichambaService.cancelContract(id).subscribe(
      (data: any) => {
        this.getccontracts();
        this.alertService.presentToast(data['message']);
      }, (error: any) => {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
      });
    //}
  }

  async presentAlert(id: String) {
    const alert = await this.alertController.create({
      header: 'Atención',
      message: 'Si cancela un servicio sin 24 horas de anticipación, no se devolverá el monto total. ¿Está seguro de que desea cancelar?',
      cssClass: 'light',
      buttons: [
        {
          text: 'Cancelar',
          role: 'cancel',
          cssClass: 'secondary',
        },
        {
          text: 'Confirmar',
          handler: () => {
            this.ichambaService.cancelContract(id).subscribe(
              (data: any) => {
                this.getccontracts();
                this.alertService.presentToast(data['message']);
              }, (error: any) => {
                this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
              });
          }
      }]
  });
    await alert.present();
  }

}
