import { AfterViewInit, Component, ElementRef, OnInit, inject, signal, viewChild } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, RouterModule } from '@angular/router';

import { PasswordResetFinishService } from './password-reset-finish.service';
import SharedModule from '../../../shared/shared.module';
import {APP_CONFIG, appConfig, VALIDATION_MESSAGES} from '../../../app.config';

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

  initialized = signal(false);
  doNotMatch = signal(false);
  error = signal(false);
  success = signal(false);
  key = signal('');

  readonly validationMessages = VALIDATION_MESSAGES;
  readonly passwordConfig = APP_CONFIG.password;
  passwordForm = new FormGroup({
    newPassword: new FormControl('', {
      nonNullable: true,
      validators: [
        Validators.required,
        Validators.minLength(APP_CONFIG.password.minLength),
        Validators.maxLength(APP_CONFIG.password.maxLength)
      ],
    }),
    confirmPassword: new FormControl('', {
      nonNullable: true,
      validators: [
        Validators.required,
        Validators.minLength(APP_CONFIG.password.minLength),
        Validators.maxLength(APP_CONFIG.password.maxLength)
      ],
    }),
  });

  private readonly passwordResetFinishService = inject(PasswordResetFinishService);
  private readonly route = inject(ActivatedRoute);

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      if (params["key"]) {
        this.key.set(params["key"]);
      }
      this.initialized.set(true);
    });
  }

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

  finishReset(): void {
    this.doNotMatch.set(false);
    this.error.set(false);

    const { newPassword, confirmPassword } = this.passwordForm.getRawValue();

    if (newPassword !== confirmPassword) {
      this.doNotMatch.set(true);
    } else {
      this.passwordResetFinishService.save(this.key(), newPassword).subscribe({
        next: () => this.success.set(true),
        error: () => this.error.set(true),
      });
    }
  }

  protected readonly appConfig = appConfig;
  protected readonly APP_CONFIG = APP_CONFIG;
}
