import { Component, ChangeDetectorRef } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { IchambaService } from 'src/app/services/ichamba.service';
import { AlertService } from 'src/app/services/alert.service';
import { ReportDiscussionPage } from '../../report-discussion/report-discussion.page';

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

  reports: any[] = [];
  reports_dates: string[] = [];
  loading = true;

  constructor(
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private cdr: ChangeDetectorRef,
    private modalCtrl: ModalController,
  ) { }

  ionViewWillEnter() {
    this.loading = true;
    this.loadReports();
  }

  refresh(event: any) {
    this.ichambaService.getPostulationReports().subscribe({
      next: data => {
        this.reports = data;
        this.buildDates();
        this.cdr.detectChanges();
        event.target.complete();
      },
      error: error => {
        this.alertService.presentToast('Por favor contacte a soporte técnico, Estatus:' + error['status']);
        event.target.complete();
      }
    });
  }

  loadReports() {
    this.ichambaService.getPostulationReports().subscribe({
      next: data => {
        this.reports = data;
        this.buildDates();
        this.loading = false;
        this.cdr.detectChanges();
      },
      error: error => {
        this.loading = false;
        this.alertService.presentToast('Por favor contacte a soporte técnico, Estatus:' + error['status']);
      }
    });
  }

  async viewDiscussion(reportId: any) {
    const modal = await this.modalCtrl.create({
      component: ReportDiscussionPage,
      componentProps: { reportId },
    });
    await modal.present();
  }

  private buildDates() {
    this.reports_dates = this.reports.map(r =>
      new Date((new Date(r.appointment).toLocaleString('en-US') + ' UTC').replace(',', '')).toLocaleDateString('es-US', {
        weekday: 'long', year: 'numeric', month: 'short', day: 'numeric',
        hour: 'numeric', minute: 'numeric', timeZoneName: 'long'
      })
    );
  }
}
