import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { HeaderComponent } from '../header/header.component';

@Component({
  selector: 'app-reset-password',
  standalone: true,
  imports: [CommonModule, FormsModule, HttpClientModule, RouterModule, HeaderComponent],
  templateUrl: './reset-password.component.html',
  styleUrls: ['./reset-password.component.css']
})
export class ResetPasswordComponent {
  password = '';
  confirmPassword = '';
  token = '';
  message = '';
  error = '';
  loading = true;
  valid = false;
  success = false;

  constructor(private route: ActivatedRoute, private http: HttpClient, private router: Router) {
    this.route.queryParams.subscribe(params => {
      this.token = params['token'] || '';
      this.error = params['error'] || '';
      
      if (this.error) {
        this.loading = false;
        this.error = 'Invalid or expired token. Please request a new reset link.';
        return;
      }

      if (this.token) {
        this.validateToken();
      } else {
        this.error = 'Invalid reset link. Missing token parameter.';
        this.loading = false;
      }
    });
  }

  validateToken() {
    this.http.post<any>('https://infoways.in/funtelapi/forgot_password.php', {
      action: 'check',
      token: this.token
    }).subscribe({
      next: res => {
        this.valid = res.status === 'success';
        this.loading = false;
        if (!this.valid) {
          this.error = res.message || 'Invalid or expired token. Please request a new reset link.';
        }
      },
      error: (err) => {
        this.loading = false;
        this.error = err.error?.message || 'Unable to validate token. Please try again.';
      }
    });
  }

  isStrongPassword(password: string): boolean {
    // Must have 1 uppercase, 1 lowercase, 1 number, 1 special char, min 8 chars
    const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
    return strongRegex.test(password);
  }

  onSubmit() {
    this.error = '';
    this.message = '';

    if (this.password !== this.confirmPassword) {
      this.error = 'Passwords do not match.';
      return;
    }

    if (!this.isStrongPassword(this.password)) {
      this.error = 'Password must be at least 8 characters long and include: 1 uppercase, 1 lowercase, 1 number, and 1 special character.';
      return;
    }

    this.http.post<any>('https://infoways.in/funtelapi/forgot_password.php', {
      action: 'reset-password',
      token: this.token,
      password: this.password
    }).subscribe({
      next: (res) => {
        if (res.status === 'success') {
          this.success = true;
          this.message = '✅ Your password has been reset successfully!';
        } else {
          this.error = res.message || 'Password reset failed.';
        }
      },
      error: (err) => {
        this.error = err.error?.message || 'Password reset failed. Please try again.';
      }
    });
  }
  loginredirect() {
    this.router.navigate(['/login']);
  }
}
