import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-forgot-password',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterModule],
  templateUrl: './forgot-password.component.html',
  styleUrl: './forgot-password.component.scss'
})
export class ForgotPasswordComponent {
  email = '';
  error: string | null = null;
  success: string | null = null;
  loading = false;
  emailError = '';

  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  validateEmail() {
    this.emailError = '';
    if (!this.email) {
      return;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(this.email)) {
      this.emailError = 'Please enter a valid email address';
    }
  }

  async submit() {
    this.error = null;
    this.success = null;
    this.emailError = '';

    if (!this.email) {
      this.emailError = 'Email is required';
      return;
    }

    this.validateEmail();
    if (this.emailError) {
      return;
    }

    this.loading = true;
    try {
      const result = await this.auth.forgotPassword(this.email);
      this.success = result.message || 'If an account with that email exists, a password reset link has been sent.';
      this.email = '';
    } catch (e: any) {
      this.error = e?.response?.data?.message || e?.response?.data?.error || 'Failed to send password reset email. Please try again.';
    } finally {
      this.loading = false;
    }
  }
}

