import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MateriaisService } from '../../services/materiais.service';
import { Material } from '../../models/material.model';
import { CleanFilenamePipe } from '../../pipes/clean-filename.pipe';

@Component({
  selector: 'app-materialFuncionario',
  standalone: true,
  imports: [
    FormsModule,
    CommonModule,
    RouterModule,
    CleanFilenamePipe
  ],
  templateUrl: './materialFuncionario.component.html',
  styleUrls: ['./materialFuncionario.component.css']
})
export class MaterialFuncionarioComponent implements OnInit {

  dicasDeSaude: Material[] = [];
  dicaSelecionada: Material | null = null;

  constructor(private materiaisService: MateriaisService) { }

  ngOnInit() {
    this.carregarDicas();
  }

  carregarDicas() {
    this.materiaisService.listarMateriais().subscribe({
      next: (dados) => this.dicasDeSaude = dados,
      error: (err) => console.error('Erro ao carregar materiais', err)
    });
  }

  abrirDica(dica: Material) {
    this.dicaSelecionada = dica;
  }

  fecharPopUp() {
    this.dicaSelecionada = null;
  }

  downloadPDF(fileName: string) {
    this.materiaisService.downloadArquivo(fileName).subscribe(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      a.click();
      window.URL.revokeObjectURL(url);
    });
  }
}
