import {Component, Input, OnDestroy, OnInit} from '@angular/core';
import {HeaderComponent} from '../header/header.component';
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';

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

  constructor(private formBuilder: FormBuilder,
              private authorService: AuthorService,
              private router: Router,
              private messageService: MessageService
  ) {
    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: 'READER', disabled: !this.adminForm}, [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.authorService.createAccountAdmin(this.username, this.password, this.role); //TODO à finir
      } 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.message)

        }));
      }
    }
  }


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


}
