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

@Component({
  selector: 'app-reset-password',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterModule],
  templateUrl: './reset-password.component.html',
  styleUrl: './reset-password.component.scss'
})
export class ResetPasswordComponent implements OnInit {
  token = '';
  newPassword = '';
  confirmPassword = '';
  error: string | null = null;
  success: string | null = null;
  loading = false;
  passwordError = '';
  confirmPasswordError = '';
  showPassword = false;
  showConfirmPassword = false;

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

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.token = params['token'] || '';
      if (!this.token) {
        this.error = 'Invalid reset link. Please request a new password reset.';
      }
    });
  }

  validatePassword() {
    this.passwordError = '';
    if (!this.newPassword) {
      return;
    }
    if (this.newPassword.length < 8) {
      this.passwordError = 'Password must be at least 8 characters long';
    }
  }

  validateConfirmPassword() {
    this.confirmPasswordError = '';
    if (!this.confirmPassword) {
      return;
    }
    if (this.newPassword !== this.confirmPassword) {
      this.confirmPasswordError = 'Passwords do not match';
    }
  }

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

    if (!this.token) {
      this.error = 'Invalid reset link. Please request a new password reset.';
      return;
    }

    if (!this.newPassword) {
      this.passwordError = 'Password is required';
      return;
    }

    this.validatePassword();
    if (this.passwordError) {
      return;
    }

    if (!this.confirmPassword) {
      this.confirmPasswordError = 'Please confirm your password';
      return;
    }

    this.validateConfirmPassword();
    if (this.confirmPasswordError) {
      return;
    }

    this.loading = true;
    try {
      const result = await this.auth.resetPassword(this.token, this.newPassword, this.confirmPassword);
      this.success = result.message || 'Password has been reset successfully.';
      setTimeout(() => {
        this.router.navigate(['/login']);
      }, 2000);
    } catch (e: any) {
      this.error = e?.response?.data?.message || e?.response?.data?.error || 'Failed to reset password. Please try again.';
    } finally {
      this.loading = false;
    }
  }

  togglePasswordVisibility() {
    this.showPassword = !this.showPassword;
  }

  toggleConfirmPasswordVisibility() {
    this.showConfirmPassword = !this.showConfirmPassword;
  }
}

