import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ResetPasswordService } from './reset-pass.service'; // Assuming resetPassService handles JWT validation and user details
import { ToastService } from 'src/app/toast/toast-service';

@Component({
  selector: 'app-reset-password',
  templateUrl: './reset-password.component.html',
  styleUrls: ['./reset-password.component.scss']
})
export class ResetPasswordComponent implements OnInit {
  resetForm: FormGroup;
  userProfile: any; // Assuming userProfile contains user details fetched from backend
  isTokenExpired: boolean = false;
  message="";

  constructor(
    private fb: FormBuilder,
    private resetPassService: ResetPasswordService, // Service to handle JWT and user details
    private router: Router,
    private route: ActivatedRoute,
    private toastService: ToastService
  ) { }

  ngOnInit(): void {
    this.initForm();
    this.getUserProfile();
  }

  initForm(): void {
    this.resetForm = this.fb.group({
      username: [{ value: '', disabled: true }],
      newPassword: ['', Validators.required],
      retypePassword: ['', Validators.required]
    });
  }
  gotoForgotPass(){
    this.router.navigate(['/account/forgot-password'])
  }

  getUserProfile(): void {
    const token = this.getJwtTokenFromUrl(); // Retrieve JWT token from resetPassService
    if (token) {
      const decodedToken = this.resetPassService.decodeJwt(token);
      if (decodedToken) {
        const username = decodedToken.sub;
        this.resetForm.controls['username'].setValue(username);
        // Assuming backend API to fetch user details using username/sub from token
        const currentTime = Date.now() / 1000; // Get current time in seconds
        if (decodedToken.exp < currentTime) {
          console.log('Token has expired');
          this.isTokenExpired = true;
          this.message="Link expired create new one....!";
          // Optionally, navigate to an error page or show an error message
        } else {
          this.isTokenExpired=false;
          this.resetPassService.getUserDetails(username).subscribe(
            (data: any) => {
              this.userProfile = data; // Assuming user profile data structure
              this.resetForm.patchValue({ username: this.userProfile.username });

            },
            error => {
              console.error('Error fetching user details:', error);
            }
          );
        }  
        
      }
    }
    else{
      this.router.navigate(['/account/forgot-password'])
    }
  }
  getJwtTokenFromUrl(): string | null {
    return this.route.snapshot.queryParamMap.get('token');
  }

  onSubmit(): void {
    if (this.resetForm.valid) {
      const formData = this.resetForm.value;
      if (formData.newPassword === formData.retypePassword) {
        // Assuming backend API to update password
        this.resetPassService.updatePassword(this.userProfile.id, formData.newPassword).subscribe(
          (response: any) => {
            console.log('Password updated successfully:', response);

            this.toastService.show('Password updated successfully!', { classname: 'bg-success text-light', delay: 3000 });

            this.isTokenExpired = true;
            setTimeout(() => {
              this.router.navigate(['/account/login']);
            }, 5000);
            this.router.navigate(['/account/login']);
            // Optionally, navigate to a success page or notify the user
          },
          error => {
            console.error('Failed to update password:', error);
            this.toastService.show('Failed to update password!', { classname: 'bg-error text-light', delay: 3000 });

            // Handle error: show error message or handle as needed
          }
        );
      } else {
        console.error('Passwords do not match');
        this.toastService.show('Passwords do not match!', { classname: 'bg-error text-light', delay: 3000 });
      }
    } else {
      console.error('Form is invalid');
      this.toastService.show('Please add password!', { classname: 'bg-error text-light', delay: 3000 });
      // Handle form validation errors
    }
  }
}
