import { Component, EventEmitter, Output, signal, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { AuthService } from '@service/auth.service';

@Component({
  selector: 'app-recover-password',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, RouterModule],
  templateUrl: './recover-password.component.html',
})
export default class RecoverPasswordComponent implements OnInit {
  emailForm: FormGroup;
  resetPasswordForm: FormGroup;
  errorMessage = signal('');
  successMessage = signal('');
  isLoading = signal(false);
  token = '';
  isResetMode = signal(false);

  @Output() closeDialog = new EventEmitter<void>();
  @Output() switchToLogin = new EventEmitter<void>();

  private fb = inject(FormBuilder);
  private authService = inject(AuthService);
  private router = inject(Router);
  private route = inject(ActivatedRoute);

  constructor() {
    this.emailForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
    });

    this.resetPasswordForm = this.fb.group(
      {
        password: ['', [Validators.required, Validators.minLength(8)]],
        confirmPassword: ['', [Validators.required]],
      },
      {
        validators: this.passwordMatchValidator,
      }
    );
  }

  ngOnInit(): void {
    // Check if we're in reset mode via URL parameters
    // This is still needed for direct access via URLs with token
    this.route.queryParamMap.subscribe((params) => {
      const token = params.get('token');
      if (token) {
        this.token = token;
        this.isResetMode.set(true);
      }
    });
  }

  passwordMatchValidator(form: FormGroup) {
    const password = form.get('password')?.value;
    const confirmPassword = form.get('confirmPassword')?.value;
    return password === confirmPassword ? null : { passwordMismatch: true };
  }

  get emailFormControls() {
    return this.emailForm.controls;
  }

  get resetFormControls() {
    return this.resetPasswordForm.controls;
  }

  onSubmitEmail(): void {
    if (this.emailForm.invalid) {
      return;
    }

    this.isLoading.set(true);
    this.errorMessage.set('');
    this.successMessage.set('');

    const email = this.emailFormControls['email'].value;

    this.authService.recoverPassword(email).subscribe({
      next: () => {
        this.isLoading.set(false);
        this.successMessage.set(
          'Wenn ein Konto mit dieser E-Mail existiert, wird eine E-Mail mit weiteren Anweisungen gesendet.'
        );
        this.emailForm.reset();
        setTimeout(() => {
          this.closeDialog.emit();
          this.switchToLogin.emit();
        }, 2000);
      },
      error: (err) => {
        this.isLoading.set(false);
        this.errorMessage.set(
          err.error?.message || 'Ein Fehler ist aufgetreten. Bitte versuche es später erneut.'
        );
      },
    });
  }

  onSubmitReset(): void {
    if (this.resetPasswordForm.invalid) {
      return;
    }

    this.isLoading.set(true);
    this.errorMessage.set('');
    this.successMessage.set('');

    const password = this.resetFormControls['password'].value;

    this.authService.resetPassword(this.token, password).subscribe({
      next: () => {
        this.isLoading.set(false);
        this.successMessage.set(
          'Dein Passwort wurde erfolgreich zurückgesetzt. Du kannst dich jetzt anmelden.'
        );
        setTimeout(() => {
          this.closeDialog.emit();
          this.switchToLogin.emit();
        }, 3000);
      },
      error: (err) => {
        this.isLoading.set(false);
        this.errorMessage.set(
          err.error?.message || 'Ein Fehler ist aufgetreten. Bitte versuche es später erneut.'
        );
      },
    });
  }

  goBackToLogin(): void {
    this.switchToLogin.emit();
  }
}
