import {Component, EventEmitter, Input, OnDestroy, Output} from '@angular/core';
import {Button} from 'primeng/button';
import {InputTextModule} from 'primeng/inputtext';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {SelectButtonModule} from 'primeng/selectbutton';
import {Subscription, switchMap} from 'rxjs';
import {AuthorService} from '../../services/author.service';
import {MessageService} from 'primeng/api';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {Author} from '../../models/author';
import {Router} from '@angular/router';
import {AuthService} from '../../auth.service';

@Component({
  selector: 'app-update-profile',
  standalone: true,
  imports: [
    Button,
    InputTextModule,
    ReactiveFormsModule,
    SelectButtonModule,
    FileUploadModule
  ],
  templateUrl: './update-profile-form.component.html',
  styleUrl: './update-profile-form.component.css'
})
export class UpdateProfileFormComponent implements OnDestroy {
  @Input() username: string = "";
  @Input() authorId: string = "";
  password: string = "";
  passwordConfirm: string = "";
  @Output() updatedAuthorEvent: EventEmitter<Author> = new EventEmitter();
  uploadedFile: File | undefined;
  subs: Subscription[] = [];
  form: FormGroup;

  constructor(private formBuilder: FormBuilder,
              private authorService: AuthorService,
              private messageService: MessageService,
              private authService: AuthService,
              private router: Router,
  ) {
    this.form = this.formBuilder.group({
      username: ['', [Validators.required, Validators.maxLength(255)]],
      password: ['', [Validators.required, Validators.maxLength(50)]],
      passwordConfirm: ['', [Validators.required, Validators.maxLength(50)]],
    });
  }

  onSelected(event: FileSelectEvent): void {
    if (event.currentFiles && event.currentFiles.length > 0) {
      this.uploadedFile = event.currentFiles[0];
    }
  }

  choose(callback: Function) {
    callback();
  }

  successMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'success',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  failureMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'error',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  onSubmit() {
    const token = this.authService.getAuthenticatedAuthorToken();
    if (this.form.valid && token && this.password === this.passwordConfirm) {
      const newUsername = this.form.value.username;
      if (this.uploadedFile) {
        this.subs.push(this.authorService.updateAuthor(this.authorId, token, newUsername, this.password).pipe(
          switchMap((_) => {
            return this.authorService.changeAvatar(this.authorId, this.uploadedFile, token)
          })
        ).subscribe({
          next: (author: Author) => {
            this.successMessage("Mise à jour réussie", "Profil mit à jour avec succès");
            this.updatedAuthorEvent.emit(author);
            sessionStorage.setItem('author', JSON.stringify(author));
            this.router.navigate(['/']);
          },
          error: (err) => {
            this.failureMessage("Erreur", err.error.error.message);
          }
        }));
      } else {
        this.subs.push(this.authorService.updateAuthor(this.authorId, token, newUsername, this.password).subscribe({
          next: (author: Author) => {
            this.successMessage("Mise à jour réussie", "Profil mit à jour avec succès");
            this.updatedAuthorEvent.emit(author);
            sessionStorage.setItem('author', JSON.stringify(author));
            this.router.navigate(['/']);
          },
          error: (err) => {
            this.failureMessage("Erreur", err.error.error.message);
          }
        }));
      }
    }

  }

  ngOnDestroy(): void {
    this.subs.forEach(sub => sub.unsubscribe())
  }

}
