import { Component, OnInit } from '@angular/core';
import { User } from '../model/user.model';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { ForgotPasswordEmailVerificationService } from './service/forgot-password-email-verification-service.service';
import { environment } from '../environments/environment';
import { RegistrationService } from '../registration/service/Registration.service';

@Component({
    selector: 'app-forgot-password-email-verification',
    templateUrl: './forgot-password-email-verification.component.html',
    styleUrls: ['./forgot-password-email-verification.component.css'],
    standalone: false
})
export class ForgotPasswordEmailVerificationComponent implements OnInit{

  user: User = new User();
  otp: number | null = null;
  isOtpSent: boolean = false;
display:string;

  constructor(private forgotPasswordEmailVerificationService: ForgotPasswordEmailVerificationService, private router: Router,
    private toastr: ToastrService, private route: ActivatedRoute, private registrationService:RegistrationService) {}

    envName=environment.envName;
   ngOnInit(): void {

    this.getRegularExpressionForEmail();
   }

  verifyEmail() {
    if (!this.user.userId || !this.isValidEmail(this.user.userId)) {
      this.toastr.error('Please enter a valid email address.');
      return;
    }
  
    this.forgotPasswordEmailVerificationService.verifyUserEmail(this.user.userId).subscribe(
      (response) => {
        if (response) {
          this.sendOtp();
        } else {
          this.toastr.error('User not found.');
        }
      },
      (error) => {
        //console.error('Verification failed', error);
        if (error.status === 404) {
          this.toastr.error('User not found.');
        } else {
          this.toastr.error('An error occurred while verifying the email.');
        }
      }
    );
  }

  sendOtp() {
    this.forgotPasswordEmailVerificationService.getOtpForUser(this.user.userId).subscribe(
      (otp) => {
        // this.otp = otp;
        this.isOtpSent = true;
        ////console.log(otp);
        this.toastr.success('OTP sent successfully to your email ID.');
        this.router.navigate(['/f-p-o-v'], {
          queryParams: { email: this.user.userId }
        });
      },
      (error) => {
        this.toastr.error('An error occurred while sending OTP.');
      }
    );
  }


  isValidEmail(email: string): boolean {
    const emailPattern = new RegExp(this.regExp.trim()); // Use the fetched regex pattern
    return emailPattern.test(email);
  }
  backButton(){
    this.router.navigateByUrl('/login');
  }

   regExp: string = '';
      getRegularExpressionForEmail() {
        // Assuming 'this.assetService' is where getEmailReqExp is defined
        this.registrationService.getEmailReqExp('email').subscribe({
          next: (response: string) => { // 👈 Make sure to expect a string here
            // 'response' is ALREADY the extracted 'value' string from the map operator.
            const respo = response[0] as any;
            this.regExp = respo.value.trim(); // Trim any whitespace
            //console.log('Email regex fetched and assigned:', this.regExp);
          },
          error: (error) => {
            //console.error('Error fetching email regex:', error);
            // Handle the error, e.g., set a default value or clear regExp
            this.regExp = ''; // Or null, depending on your default state
          }
        });
      }
   
}
