import { Component, OnInit, Input, inject } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { FormBuilder, FormGroup, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AlertService } from '../alert';
import { UserService } from '../../../providers/user/user.service.';
import { NgClass } from '@angular/common';

@Component({
  standalone: true,
  selector: 'app-otp',
  templateUrl: './otp.component.html',
  imports: [FormsModule, ReactiveFormsModule, NgClass]
})
export class OtpComponent implements OnInit
{
  private readonly user = inject(UserService);
  private readonly formBuilder = inject(FormBuilder);
  private readonly alertService = inject(AlertService);
  private readonly activeModal = inject(NgbActiveModal);

  @Input() fromParent;

  public otpForm: FormGroup;
  public userId: number = 0;
  public authMethod: number = 0;
  public submitted: boolean = false;

  ngOnInit()
  {
    this.userId = this.fromParent.userId;
    this.authMethod = this.fromParent.authMethod;
    this.otpForm = this.formBuilder.group({ otpCode: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(6)]] });
  }

  get f() { return this.otpForm.controls; }

  public validateOtp(): void
  {
    this.submitted = true;
    this.alertService.clear();
    if (this.otpForm.invalid)
      return;

    this.user.validateOtp(this.userId, this.authMethod, this.f.otpCode.value).subscribe(
      {
        next: (resp: any) =>
        {
          if (resp.returnStatus === 200 && resp.value)
          {
            this.activeModal.close(true);
          }
          else
          {
            this.alertService.error(resp.returnMessage);
          }
        },
        error: (errorMessage: string) =>
        {
          this.alertService.error(errorMessage);
        }
      });
  }

  public close(): void
  {
    this.activeModal.close(false);
  }
}
