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

@Component({
  selector: 'app-register-form',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    InputTextModule,
    SelectButtonModule,
    FormsModule,
    Button
  ],
  templateUrl: './register-form.component.html',
  styleUrl: './register-form.component.css'
})
export class RegisterFormComponent implements OnDestroy {
  @Input() username: string = "";
  @Output() createdAuthor: EventEmitter<Author> = new EventEmitter();
  @Input() password: string = "";
  @Input() passwordConfirm: string = "";
  @Input() role: string = Role.READER
  @Input() adminForm: boolean = false;
  roles = [
    {name: 'Lecteur', value: Role.READER},
    {name: 'Écrivain', value: Role.WRITER}
  ];
  subs: Subscription[] = [];
  form: FormGroup;
  actualAuthor: string | undefined;

  constructor(private formBuilder: FormBuilder,
              private authorService: AuthorService,
              private router: Router,
              private messageService: MessageService,
              private authService: AuthService,
  ) {
    const authenticatedAuthor = this.authService.getAuthenticatedAuthorToken();
    if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated() && authenticatedAuthor) {
      this.actualAuthor = authenticatedAuthor;
    }
    this.form = this.formBuilder.group({
      username: ['', [Validators.required, Validators.maxLength(255)]],
      password: ['', [Validators.required, Validators.maxLength(50)]],
      passwordConfirm: ['', [Validators.required, Validators.maxLength(50)]],
      role: [{value: Role.READER}, [Validators.required, Validators.maxLength(10)]],
    });
  }

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

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

  onSubmit() {
    if (this.form.valid && this.password === this.passwordConfirm) {
      if (this.adminForm && this.actualAuthor) {
        this.authorService.createAccountAdmin(
          this.username,
          this.password,
          this.role,
          this.authService.getAuthenticatedAuthorToken()!).subscribe({
          next: (author: Author) => {
            this.successMessage('Succès', `Auteur ${author.name} créé avec succès`);
            this.createdAuthor.emit(author);
          },
          error: (err) => {
            this.failureMessage("Erreur", err.error.message);
          }
        });
      } else {
        this.subs.push(this.authorService.createAccount(this.username, this.password).subscribe({
          next: () => this.router.navigate(['/login']).then(() => this.successMessage('Succès', 'Utilisateur créé avec succès')),
          error: (err) => this.failureMessage('Erreur', err.error.message)

        }));
      }
    } else {
      this.failureMessage('Erreur', 'Le formulaire n\'est pas complet ou les mot de passes ne correspondent pas');
    }
  }


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


}
