import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
import { SafePipe } from '../../../pipes/safe.pipe';
import { ButtonModule } from 'primeng/button';
import { ToastModule } from 'primeng/toast';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { MessageService } from 'primeng/api';

import { PdfService } from '../../services/pdf.service';
import { AlertService } from '../../services/alert.service';

@Component({
  selector: 'app-visor-pdf',
  standalone: true,
  imports: [
    CommonModule,
    SafePipe,
    ButtonModule,
    ToastModule,
    ProgressSpinnerModule
  ],
  templateUrl: './visor-pdf.component.html',
  styleUrls: ['./visor-pdf.component.scss']
})
export class VisorPdfComponent implements OnInit {
  product: any;
  pdfSrc: string = '';
  enviando: boolean = false;

  // Inyectar servicios usando la nueva sintaxis de Angular
  private dialogRef = inject(DynamicDialogRef);
  private config = inject(DynamicDialogConfig);
  private messageService = inject(MessageService);
  private pdfService = inject(PdfService);
  private alertService = inject(AlertService);

  ngOnInit() {
    // Obtener el producto pasado a través del servicio de diálogo
    this.product = this.config.data?.product;

    // Generar el PDF
    this.generarPDF();
  }

  generarPDF() {
    this.pdfService.generateCronogramaPdf(this.product).then(dataUrl => {
      this.pdfSrc = dataUrl;
    });
  }

  descargarPDF() {
    this.pdfService.downloadCronogramaPdf('cronograma', this.product);
  }

  enviarPDF() {
    this.enviando = true;
    console.log('Enviando PDF...');

    setTimeout(() => {
      this.enviando = false;
      console.log('Mostrando mensaje de envio...')
      this.alertService.success(
        'El cronograma ha sido enviado correctamente a la plataforma.',
        '¡Enviado con éxito!'
      );
    }, 2000);
  }

  cerrar() {
    this.dialogRef.close();
  }
}