import { Component, OnInit } from '@angular/core';
import { MenuController, NavController, LoadingController } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { AlertService } from 'src/app/services/alert.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { TranslateService } from '@ngx-translate/core';
import { LanguageService } from 'src/app/services/language.service';
import { User } from 'src/app/models/user';
// TODO: Install and configure OneSignal Capacitor plugin for push notifications
// import OneSignal from 'onesignal-cordova-plugin';

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

  private loading: any;
  user!: User;
  userName: string = '';
  categories: any[] = [];
  aux_categories: any[] = [];
  showList: boolean = false;
  pcontracts: any[] = [];
  pcontracts_dates: any[] = [];
  ccontracts: any[] = [];
  ccontracts_dates: any[] = [];
  isContract: boolean = false;
  lang: boolean = false;

  constructor(
    private menu: MenuController,
    private navCtrl: NavController,
    public authService: AuthService,
    private ichambaService: IchambaService,
    private alertService: AlertService,
    private translateService: TranslateService,
    private languageService: LanguageService,
    private loadingCtrl: LoadingController
  ) {
    this.menu.enable(true);
  }

  ngOnInit() {
    if (this.languageService.getDefaultLanguage() == 'es') {
      this.lang = true;
      this.ichambaService.getCategories()
        .subscribe( categories => {
          this.categories = categories;
          this.aux_categories = categories;
        })
    }
    else {
      this.lang = false;
      this.ichambaService.getEnCategories()
        .subscribe( categories => {
          this.categories = categories;
          this.aux_categories = categories;
        })
    }
    this.getpcontracts();
    this.getccontracts();
  }

  refresh(event: any) {
    this.getpcontracts();
    this.ichambaService.getCurrentcontracts().subscribe(
      data => {
        this.ccontracts = data;
        for (var i of this.ccontracts) {
          if (this.languageService.getDefaultLanguage() == 'es') {
            this.ccontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace("," ,"")).toLocaleDateString('es-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'long'}));
          } else {
            this.ccontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace("," ,"")).toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'long'}));
          }
        }
        if (!this.ccontracts.length) {
          console.log("vacio");
          this.isContract = false;
        } else {
          this.isContract = true;
        }
        event.target.complete();
      }, error => {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
        event.target.complete();
      });
  }

  getpcontracts() {
    this.ichambaService.getPendingcontracts().subscribe(
      data => {
        this.pcontracts = data;
        for (var i of this.pcontracts) {
          if (this.languageService.getDefaultLanguage() == 'es') {
            this.pcontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace("," ,"")).toLocaleDateString('es-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'long'}));
          } else {
            this.pcontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace("," ,"")).toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'long'}));
          }
        }
        if (!this.pcontracts.length) {
          console.log("vacio");
          this.isContract = false;
        } else {
          this.isContract = true;
        }
      }, error => {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
      });
  }

  getccontracts() {
    this.ichambaService.getCurrentcontracts().subscribe(
      data => {
        this.ccontracts = data;
        for (var i of this.ccontracts) {
          if (this.languageService.getDefaultLanguage() == 'es') {
            this.ccontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace("," ,"")).toLocaleDateString('es-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'long'}));
          } else {
            this.ccontracts_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace("," ,"")).toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'long'}));
          }
        }
        if (!this.ccontracts.length) {
          console.log("vacio");
          this.isContract = false;
        } else {
          this.isContract = true;
        }
      }, error => {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
      });
  }

  viewsuppliers(postulation_id: String) {
    this.navCtrl.navigateForward(['/viewsuppliers/', postulation_id]);
  }

  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']);
      });
    //}
  }

  search (ev: any) {
    this.categories = this.aux_categories;

    console.log(ev);
    let val = ev.detail.value || ev.target.value;

   // if the value is an empty string don't filter the items
     if (val && val.trim() != '') {

       // Filter the items
       this.categories = this.categories.filter((category) => {
         return (category.toLowerCase().indexOf(val.toLowerCase()) > -1);
       });

       // Show the results
       this.showList = true;
     } else {

     // hide the results when the query is empty
       this.showList = false;
     }
  }

check(category_string: String) {
  this.loadingCtrl.create().then((overlay) => {
    this.loading = overlay;
    this.loading.present();
  });
    this.ichambaService.checkCategories(category_string)
      .subscribe( check => {
        if (check != null) {
          this.loading.dismiss();
          this.navCtrl.navigateForward(['/category/', category_string])
        } else {
          this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.no_service'));
        }
      }, error => {
        this.loading.dismiss();
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
      }
    )
  }

  ionViewWillEnter() {
    this.authService.user().subscribe({ error: () => {} });
  }
}
