import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { AuthService } from '../../../services/auth.service'; // Use AuthService
import { PasswordResetRequest } from '../../../models/auth/auth.model'; // Import PasswordResetRequest DTO

@Component({
  selector: 'app-forgotpassword',
  templateUrl: './forgotpassword.component.html',
  styleUrls: ['./forgotpassword.component.scss']
})
export class ForgotpasswordComponent implements OnInit {
 public emailCheckForm: FormGroup;
  emailErrMsg: string = ""
emailsend;
  constructor(private _fb: FormBuilder,
    private router: Router,
    private route:ActivatedRoute,
    private toastr:ToastrService,
    private authService: AuthService) { } // Inject AuthService

  ngOnInit(): void {
    this.emailCheckForm = this._fb.group({
      email: ['', [Validators.required, Validators.email]]
    });
  }
  onsubmit(){
    if (this.emailCheckForm.invalid) {
      return;
    }

    const request: PasswordResetRequest = { email: this.emailCheckForm.value.email };
    this.authService.initiatePasswordReset(request).subscribe(
      (response) => {
        this.emailsend = true; // Indicate success
        this.toastr.success('Password reset link sent to your email.', 'Success');
        // Optionally redirect or show a message
      },
      (errResponse: HttpErrorResponse) => {
        this.emailsend = false; // Indicate failure
        switch (errResponse.status) {
          case 400:
            this.emailErrMsg = 'Invalid email address or user not found.';
            break;
          case 500:
            this.emailErrMsg = 'Internal Server Error';
            break;
          default:
            this.emailErrMsg = 'Failed to send password reset link.';
            break;
        }
        this.toastr.error(this.emailErrMsg, 'Password Reset Failed');
      }
    );
    // this.emailCheckForm.reset(); // Don't reset immediately, let user see error if any
  }
  onSubmit() {
    // This method seems to be a duplicate of onsubmit, removing it.
    // The primary onsubmit method will handle the logic.
  }
  gotoreset(){
    this.router.navigate(["../forgotresetpassword"], { relativeTo: this.route });
  }
}
