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

@Component({
  selector: 'app-listar-material',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    CleanFilenamePipe
  ],
  templateUrl: './listar-material.component.html',
  styleUrls: ['./listar-material.component.css']
})
export class ListarMaterialComponent implements OnInit {
  materiais: any[] = [];

  constructor(private materialService: MateriaisService, private router: Router) {}

  ngOnInit(): void {
    this.carregarMateriais();
  }

  carregarMateriais(): void {
    this.materialService.listarMateriais().subscribe({
      next: (data) => this.materiais = data,
      error: (err) => console.error('Erro ao buscar materiais:', err)
    });
  }

  excluir(event: Event, material: any): void {
    event.preventDefault();
    if (confirm(`Tem certeza que deseja excluir o material "${material.title}"?`)) {
      this.materialService.removerMaterial(material.id).subscribe({
        next: () => {
          alert('Material removido com sucesso!');
          this.carregarMateriais();
        },
        error: (err) => {
          console.error('Erro ao excluir material:', err);
          alert('Erro ao excluir material.');
        }
      });
    }
  }

  editar(event: Event, material: any): void {
    event.preventDefault();
    this.router.navigate(['/material/editar', material.id]);
  }
}