import { HttpStatusCode } from '@angular/common/http';
import { Component, Input, OnInit } from '@angular/core';
import { lastValueFrom } from 'rxjs';
import { LoginService } from '../login/service/login.service';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
import { UserService } from '../user/service/user.service';
import { environment } from '../environments/environment';
import { AssetService } from '../asset.service';

@Component({
    selector: 'app-rgnt-otp-verification',
    templateUrl: './rgnt-otp-verification.component.html',
    styleUrls: ['./rgnt-otp-verification.component.css'],
    standalone: false
})
export class RgntOtpVerificationComponent implements OnInit {

  constructor(private loginService: LoginService,
          private toastr: ToastrService, private router: Router,
          private userService: UserService,
          private sharedService:AssetService
        ){
        
        }
        @Input() userLoggedInDetails: any; 
 async ngOnInit() {
    localStorage.removeItem('previousUrl');
    this.resetTimer();
          this.startTimer();
  }
    ngOnChanges() {
      this.user = this.userLoggedInDetails;
    }
      
        showPassword: boolean | undefined;
        
        
        otp: string ;
         envName=environment.envName;
        user = {
          email: '',
          password: '',
          loginCity:'',
          loginState:'',
          loginCountry: ''
        }
      
        isOtpValid: boolean = false;
        async login(){
          //await this.getUserByEmailId(this.user.email);
          // if(this.currentLogginInUser.isLoggedIn === true){
          //   this.toastr.error('You have already logged in...')
          //   return;
          //   //window.alert('You have already logged in...')
          // }else{
          //   this.currentLogginInUser.isLoggedIn = true;
          //   this.updateUser(this.currentLogginInUser);
          // }
          //check if OTP is valid
          // if(this.otp === undefined || this.otp === null){
          //   this.otp = 0;
          // }
          if(this.otp?.toString().length==0 || this.otp ==undefined){
            this.toastr.error('please enter otp')
            return;
          }
         // if(this.otp){}
          // this.user=JSON.parse(localStorage.getItem('rgntUser'));
         // ////console.log(this.user,this.otp)

          let otpExpired=false;
          await lastValueFrom(this.loginService.verifyOtpForLoginUserByUserId(this.user.email, this.otp)).then(
            response => {
              ////console.log(response);
          
              if (response.status === HttpStatusCode.Ok) {
                this.isOtpValid = response.body;
                this.otp = null;
                // Handle successful login (navigate to dashboard, etc.)
                //console.log("Login successful! Navigating to dashboard...");
                
                //this.userService.updateUser()

                // (Your code for successful login navigation)
              } else if (response.status === HttpStatusCode.Unauthorized) {
                this.toastr.error("OTP expired. Please resend the OTP");
                // Optionally, provide a way for the user to resend the OTP
                //console.log("OTP expired. Offering option to resend OTP...");
                // (Your code for offering OTP resend functionality)
              } else {
                // Handle unexpected errors (log, display generic error message)
                //console.error("Unexpected error during OTP verification:", response);
                this.toastr.error("An error occurred during login. Please try again.");
              }
            }
          ).catch(error => {
            // Handle potential errors during the asynchronous operation
            if (error.status === HttpStatusCode.Unauthorized) {
              this.toastr.error("OTP expired. Please resend the OTP");
              otpExpired=true
              return;
              // Optionally, provide a way for the user to resend the OTP
            
              // (Your code for offering OTP resend functionality)
            } else{
              this.toastr.error("An error occurred during login. Please try again.");
            }
            
          });
          //console.log(this.isOtpValid)
          //login to app
          if(otpExpired){
            return
          }
          if(this.isOtpValid){
            await lastValueFrom(this.loginService.userLoginToDR(this.user)).then(
              response => {
                //console.log(response.headers)
                localStorage.setItem('email', response.headers.get('email'));
                // localStorage.setItem('userRole',response.headers.get('userRole'));
                // localStorage.setItem('active',response.headers.get('active'));
                // localStorage.setItem('jwtToken',response.headers.get('token'));
                // localStorage.setItem('organisationId', response.headers.get('organisationId'));
                let LoginStatus=response.headers.get('initialLoginStatus');
                let email = localStorage.getItem('email');
                let role = response.headers.get('userRole');
                let active = response.headers.get('active');
                let organisationId = response.headers.get('organisationId');
                let token = response.headers.get('token');
                localStorage.setItem('tokn',token)
                this.sharedService.initialLoginStatus = response.headers.get('initialLoginStatus');
                this.sharedService.email = response.headers.get('email');
                this.sharedService.userRole = response.headers.get('userRole');
                this.sharedService.active = response.headers.get('active');
                this.sharedService.jwtToken = response.headers.get('token');
                this.sharedService.organisationId = response.headers.get('organisationId');
                //console.log(email);
                //console.log(email);
                //console.log(role);
                //console.log(organisationId)
                //console.log(LoginStatus);
                if(active === 'false'){
                  this.toastr.error('User Inactive');
                  return;
                }
                if(LoginStatus=='true'){
                  if(role === 'IDRBTADMIN'){
                    this.router.navigateByUrl('/rgtr-dashboard');
                    this.toastr.success('Login Successful');
                   }else{
                    this.router.navigateByUrl('/dsc-guide');
                    localStorage.setItem('pageType','user');
                    this.toastr.success('Login Successful');
                  }
                }else{
                  localStorage.setItem('tempTok',response.headers.get('token'));
                  localStorage.removeItem('jwtToken');
                  this.router.navigateByUrl('change-password');
                }
                
              },error => {
                if(error.status === HttpStatusCode.Unauthorized){
                  //console.log('sdsd')
                  this.toastr.error('Incorrect EmailId or password');
                }
              }
            )
          }
          else{
            this.toastr.error('Invalid OTP');
          }
        }
      
        toggleShowPassword() {
          this.showPassword = !this.showPassword;
        }
      
      
        
        loginUserOtp: number = 0;
        async getOtpForLoginUser(){
          // this.user=JSON.parse(localStorage.getItem('rgntUser'));
          await lastValueFrom(this.loginService.getOtpForLoginUserByUserId(this.user.email)).then(
            response => {
              if(response.status === HttpStatusCode.Ok){
                this.loginUserOtp = response.body;
                //console.log(this.loginUserOtp)
                this.toastr.success('An OTP has been sent to you email.')
                this.resetTimer();
                this.startTimer();
              }
           },error => {

  const message =
    error?.error?.message ||
    'Error while fetching OTP. Please try again.';

  this.toastr.error(message);
}
          )
        }
      
        async verifyOtpOfLoggedInUser(){
          await lastValueFrom(this.loginService.verifyOtpForLoginUserByUserId(this.user.email, this.otp)).then(
            response => {
              if(response.status === HttpStatusCode.Ok){
                //console.log(this.otp)
              }
            }
          )
        }
        

  /**
   * Start the countdown timer
   */
  time: number = environment.otpExpiryTime; // 120 seconds = 2 minutes
  display: string;
  interval;
  startTimer() {
    //console.log(this.display+"display")
    this.interval = setInterval(() => {
      if (this.time > 0) {
        this.time--;
        this.display = this.transform(this.time);
      } else {
        clearInterval(this.interval);
      }
    }, 1000);
    this.display = this.transform(this.time);
  }

  /**
   * Transform the seconds into a formatted time string (mm:ss)
   * @param value - Time in seconds
   * @returns Formatted time string (mm:ss)
   */
  transform(value: number): string {
    // console.log(environment.otpExpiryTime,value)
    const minutes: number = Math.floor(value / 60);
    const seconds: number = value - minutes * 60;
    const formattedMinutes: string = minutes < 10 ? `0${minutes}` : `${minutes}`;
    const formattedSeconds: string = seconds < 10 ? `0${seconds}` : `${seconds}`;
    return formattedMinutes + ':' + formattedSeconds;
  }

  /**
   * Pause the timer
   */
  pauseTimer() {
    clearInterval(this.interval);
  }

  /**
   * Reset the timer back to 2 minutes (05:00)
   */
  resetTimer() {
    this.pauseTimer();
    this.time = environment.otpExpiryTime;
    this.display = this.transform(this.time);
  }

  otpValidation(event: KeyboardEvent): void {
    const inputElement = event.target as HTMLInputElement;
    const key = event.key;
    const keyCode = event.keyCode;
  
    // Allow backspace, arrow keys, and tab
    if (key === 'Backspace' || keyCode === 37 || keyCode === 39 || keyCode === 9) {
      return;
    }
  
    // Prevent non-numeric characters and specific symbols
    if (!/^\d$/.test(key)) { // Use regex for cleaner numeric check
      event.preventDefault();
      return;
    }
  
    // Prevent input if OTP is already 6 digits long
    if (inputElement.value.length >= 6) {
      event.preventDefault();
    }
  }

  async updateUser(user: any){
    user.isLoggedIn = true;
    await lastValueFrom(this.userService.updateUser(user)).then(response => {
      if(response.status === HttpStatusCode.PartialContent){
        //console.log(user);
      }
    })
  }

  currentLogginInUser: any;
  async getUserByEmailId(emailId: string){
    await lastValueFrom(this.userService.getUserByEmailId(this.user.email)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.currentLogginInUser = response.body;
        }
      }
    )
  }
 
 
}
