import { Component, OnInit } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth/auth.service';
import { IonInput, IonButton, IonCard, IonCardHeader, IonCardTitle, IonCardSubtitle, IonCardContent, IonProgressBar } from '@ionic/angular/standalone';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { VerifyTwoFactorSetup } from 'src/app/graphql/mutations/auth/verifyTwoFactorSetup.mutation';

@Component({
  selector: 'app-two-factor-verify',
  templateUrl: './two-factor-verify.page.html',
  styleUrls: ['./two-factor-verify.page.scss'],
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    IonInput,
    IonButton,
    IonCard,
    IonCardHeader,
    IonCardTitle,
    IonCardSubtitle,
    IonCardContent,
    IonProgressBar
  ]
})
export class TwoFactorVerifyPage implements OnInit {
  digits: string[] = Array(6).fill('');
  loading = false;
  error: string | null = null;

  constructor(
    private apollo: Apollo,
    private router: Router,
    private authService: AuthService
  ) {}

  ngOnInit() {}

  onDigitInput(event: any, index: number) {
    const input = event.target;
    const value = input.value;
    
    // Only allow numbers
    if (!/^\d*$/.test(value)) {
      input.value = '';
      this.digits[index] = '';
      return;
    }

    // Update the digit in the array
    this.digits[index] = value;

    // If this is the last digit and it's been entered, auto-submit
    if (index === 5 && value) {
      this.verifyCode();
      return;
    }

    // Move to next input if a digit is entered
    if (value && index < 5) {
      const nextInput = document.querySelector(`.digit-input:nth-child(${index + 2})`) as HTMLInputElement;
      if (nextInput) {
        nextInput.focus();
      }
    }
  }

  onKeyDown(event: KeyboardEvent, index: number) {
    // Handle backspace
    if (event.key === 'Backspace' && !this.digits[index] && index > 0) {
      const prevInput = document.querySelector(`.digit-input:nth-child(${index})`) as HTMLInputElement;
      if (prevInput) {
        prevInput.focus();
      }
    }
  }

  get verificationCode(): string {
    return this.digits.join('');
  }

  set verificationCode(value: string) {
    // This setter is kept for compatibility with existing code
    this.digits = value.split('').slice(0, 6);
  }

  verifyCode() {
    if (this.digits.some(digit => !digit)) {
      this.error = 'Please enter a valid 6-digit code';
      return;
    }

    this.loading = true;
    this.error = null;

    this.authService.getCurrentUser().subscribe({
      next: (user) => {
        if (!user?.id) {
          this.error = 'User not found. Please try logging in again.';
          this.loading = false;
          return;
        }

        this.apollo.mutate({
          mutation: VerifyTwoFactorSetup,
          variables: {
            input: {
              userId: user.id,
              code: this.verificationCode
            }
          }
        }).subscribe({
          next: (result: any) => {
            const response = result.data.verifyTwoFactorSetup;
            
            if (response.errors && response.errors.length > 0) {
              this.error = response.message || 'Verification failed. Please try again.';
              this.loading = false;
              return;
            }

            // Store the backup codes in the auth service
            this.authService.storeBackupCodes(response.backupCodes).subscribe({
              next: () => {
                this.router.navigate(['/home']);
              },
              error: (error: Error) => {
                this.error = 'Failed to store backup codes. Please try again.';
                this.loading = false;
              }
            });
          },
          error: (error) => {
            this.error = 'Failed to verify code. Please try again.';
            this.loading = false;
          }
        });
      },
      error: (error) => {
        this.error = 'Failed to get user information. Please try logging in again.';
        this.loading = false;
      }
    });
  }
} 