import { AfterViewInit, Component, ElementRef, inject, signal, viewChild } from '@angular/core';
import { FormBuilder, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';

import { PasswordResetInitService } from './password-reset-init.service';
import { RouterLink } from '@angular/router';
import SharedModule from '../../../shared/shared.module';
import {APP_CONFIG, VALIDATION_MESSAGES} from '../../../app.config';

@Component({
  selector: 'jhi-password-reset-init',
  imports: [SharedModule, FormsModule, ReactiveFormsModule, RouterLink],
  templateUrl: './password-reset-init.component.html',
})
export default class PasswordResetInitComponent implements AfterViewInit {
  email = viewChild.required<ElementRef>('email');

  success = signal(false);
  resetRequestForm;

  readonly validationMessages = VALIDATION_MESSAGES;
  readonly emailConfig = APP_CONFIG.email;

  private readonly passwordResetInitService = inject(PasswordResetInitService);
  private readonly fb = inject(FormBuilder);

  constructor() {
    this.resetRequestForm = this.fb.group({
      email: [
        '',
        [
          Validators.required,
          Validators.minLength(APP_CONFIG.email.minLength),
          Validators.maxLength(APP_CONFIG.email.maxLength),
          Validators.email
        ]
      ],
    });
  }

  ngAfterViewInit(): void {
    this.email().nativeElement.focus();
  }

  requestReset(): void {
    this.passwordResetInitService.save(this.resetRequestForm.get(['email'])!.value).subscribe(() => this.success.set(true));
  }

  protected readonly APP_CONFIG = APP_CONFIG;
}
