import { Component, inject, OnInit, signal } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { AuthService } from '../auth.service';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-otp',
  templateUrl: './otp.component.html',
  styleUrls: ['./otp.component.scss'],
  imports: [ReactiveFormsModule, CommonModule]
})
export class OtpComponent implements OnInit {
  emailForm: FormGroup;
  otpForm: FormGroup;
  isOtpSent = signal(false);
  isVerified = signal(false);
  isError = signal(false);
  message = signal('');
  countdown = signal(0);
  timer: NodeJS.Timeout | undefined;
  returnUrl = '';
  fb: FormBuilder = inject(FormBuilder);
  authService: AuthService = inject(AuthService);
  router: Router = inject(Router);
  route: ActivatedRoute = inject(ActivatedRoute);

  constructor() {
    this.emailForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
    });

    this.otpForm = this.fb.group({
      otp: ['', [Validators.required, Validators.pattern(/^[0-9]{6}$/)]],
    });

    if(this.authService.isLoggedIn()){
      this.router.navigate(['']);
    }
  }


  ngOnInit() {
    this.returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '';
  }

  sendOtp() {
    if (this.emailForm.invalid) return;
    const email = this.emailForm.value.email;

    this.authService.sendOtp(email).subscribe(() => {
      this.isOtpSent.set(true);
      this.message.set('OTP sent successfully!');
      this.startTimer(30); // 30 seconds countdown
    });
  }

  resendOtp() {
    if (this.countdown() > 0) return;
    this.sendOtp();
  }

  startTimer(seconds: number) {
    this.countdown.set(seconds);
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      this.countdown.update(value => value - 1);
      if (this.countdown() <= 0) clearInterval(this.timer);
    }, 1000);
  }

  verifyOtp() {
    if (this.otpForm.invalid) return;
    const { email: userId } = this.emailForm.value;
    const { otp: otpCode } = this.otpForm.value;

    this.authService.verifyOtp(userId, otpCode).subscribe({
      next: () => {
        this.isVerified.set(true);
        this.router.navigateByUrl(this.returnUrl); // Navigate to dashboard or desired route after successful verification
      },
      error: (err) => {
        this.isError.set(true);
        if (err.status === 401 && err.error?.message) {
          this.message.set(err.error.message);
        } else {
          this.message.set('Something went wrong. Please try again.');
        }
      }
    });
  }
}