import { Component, ChangeDetectorRef } from '@angular/core';
import { ModalController } from '@ionic/angular';
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 { ReportDiscussionPage } from '../report-discussion/report-discussion.page';

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

  reports: any[] = [];
  reports_dates: string[] = [];
  lang: boolean = false;
  loading = true;

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

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

  refresh(event: any) {
    this.reports = [];
    this.reports_dates = [];
    this.ichambaService.getReports().subscribe({
      next: data => {
        this.reports = data;
        this.buildDates();
        event.target.complete();
      },
      error: error => {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
        event.target.complete();
      }
    });
  }

  loadReports() {
    this.ichambaService.getReports().subscribe({
      next: data => {
        this.reports = data;
        this.buildDates();
        this.loading = false;
        this.cdr.detectChanges();
      },
      error: error => {
        this.loading = false;
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
      }
    });
  }

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

  getStatusColor(status: string): string {
    if (status === 'resuelto') return 'success';
    if (status === 'en revision' || status === 'en revisión') return 'primary';
    return 'warning';
  }

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