import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { MateriaisService } from '../../../services/materiais.service';
import { Material } from '../../../models/material.model';
import { AuthService, User} from '../../../services/auth.service';


@Component({
  selector: 'app-inserir-material',
  standalone: true,
  imports: [
    FormsModule,
    CommonModule,
    HttpClientModule,
    RouterModule
  ],
  templateUrl: './inserir-material.component.html',
  styleUrls: ['./inserir-material.component.css']
})
export class InserirMaterialComponent {
  material: Material = {
    titulo: '',
    conteudo: '',
    links: [],
    idAdmin: 0,
  };

  linkTemp: string = '';
  arquivoSelecionado: File | null = null;
  modalMaterial = false;
  message: string = '';


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


  onFileSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      this.arquivoSelecionado = input.files[0];
    }
  }

  salvarMaterial(): void {
    if (this.linkTemp.trim()) {
      this.material.links.push(this.linkTemp.trim());
    }
    this.authService.currentUser.subscribe((usuarioLogado: User | null) => {
      this.material.idAdmin = usuarioLogado?.id
    });
    const formData = new FormData();
    formData.append('dados', new Blob([JSON.stringify(this.material)], { type: 'application/json' }));

    if (this.arquivoSelecionado) {
      formData.append('file', this.arquivoSelecionado);
    }

    this.materialService.criarMaterial(formData).subscribe({
      next: (resposta)=>{
        console.log('Resposta do servidor:', resposta);
        this.message = resposta;
        this.modalMaterial = true;
      },
      error: (err) => {
      console.error('Erro ao criar material:', err);
      this.message = 'Falha ao criar novo material de apoio...';
      this.modalMaterial = true;
      },
    });
  }

  fecharModalEredirecionar(): void {
    this.modalMaterial = false;
    this.message ='';
    this.router.navigate(['/material']);
  }
}
