import { Component, HostListener, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { LogoLinkOptions } from '@shared/ui/logo/logo.component';
import { FormErrorsComponent } from '@shared/error-handling/form-errors/form-errors.component';
import { AuthService } from '@shared/auth/auth.service';
import { ConfigService } from '@shared/config/config.service';
import { SFALoginDataService } from '@fleio-api/second-factor-authentication/sfa-login-data.service';
import { Router } from '@angular/router';
import {
  SmsAuthenticatorAnonymousApiService
} from '@fleio-api/plugins/sms-authenticator/sms-authenticator-anonymous-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { of } from 'rxjs';
import { CookiesHelper } from '@shared/ui-api/helpers/cookies-helper';
import { ThemingService } from '@shared/ui/theming/theming.service';

@Component({
  selector: 'app-sms-authenticator-confirm-form',
  templateUrl: './sms-authenticator-confirm-form.component.html',
  styleUrls: ['./sms-authenticator-confirm-form.component.scss']
})
export class SmsAuthenticatorConfirmFormComponent implements OnInit {
  confirmLoginForm = this.formBuilder.group({
    code: ['', [Validators.required, Validators.pattern('[0-9]*')]],
    rememberSFA: [false]
  });
  logoLinkOptions = new LogoLinkOptions(false);
  receiver: string;
  verificationCodeTimeout = false;
  backendErrors = {};
  cardTopMargin: string;
  loading: boolean;

  @ViewChild('formErrors') formErrors: FormErrorsComponent;

  constructor(
    private formBuilder: UntypedFormBuilder, public auth: AuthService, public config: ConfigService,
    private sfaLoginDataService: SFALoginDataService, private router: Router,
    private smsAuthenticatorAnonymousApiService: SmsAuthenticatorAnonymousApiService,
    private notificationService: NotificationService,
    private themingService: ThemingService,
  ) {
  }

  goToConfirmOptions() {
    // prevent user from opening page in new tab
    this.router.navigateByUrl(this.config.getPanelUrl('sfa/confirm-options'));
  }

  sendCode(resend = false) {
    this.smsAuthenticatorAnonymousApiService.sendCode({
      email: this.sfaLoginDataService.email,
      password: this.sfaLoginDataService.password,
    }).subscribe(response => {
      this.receiver = response.receiver;
      if (!this.verificationCodeTimeout) {
        setTimeout(() => {
          this.verificationCodeTimeout = true;
        }, 15000);
      }
      if (resend) {
        this.notificationService.showMessage($localize`Code was sent again.`);
      }
    }, error => {
      this.verificationCodeTimeout = true;
      this.notificationService.showMessage($localize`Failed to send SMS message.`);
    });
  }

  ngOnInit() {
    if (!this.sfaLoginDataService.email) {
      return this.router.navigateByUrl(this.config.getPanelUrl('login'));
    }
    if (this.sfaLoginDataService.initializedAuthenticators.sms_authenticator) {
      this.verificationCodeTimeout = true;
    } else {
      this.sendCode();
    }
    this.sfaLoginDataService.initAuthenticator('sms_authenticator');
    this.setCardTopMargin(window.innerHeight);
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.setCardTopMargin(window.innerHeight);
  }

  private setCardTopMargin(innerHeight) {
    this.cardTopMargin = this.themingService.setOrphanCardMarginTop(innerHeight, 360);
  }

  submit() {
    if (this.confirmLoginForm.invalid) {
      return of(null);
    }
    this.loading = true;
    const value = this.confirmLoginForm.value;
    this.auth.login(
      this.sfaLoginDataService.email,
      this.sfaLoginDataService.password,
      this.sfaLoginDataService.rememberMe, {
        sfa_method_name: 'sms_authenticator',
        rememberSFA: value.rememberSFA,
        args: {
          code: value.code
        }
      }
    ).subscribe({
      next: response => {
        let rememberSFACookieSuffix: string;
        if (this.auth.feature('ui.staff')) {
          rememberSFACookieSuffix = 'staff';
        } else {
          rememberSFACookieSuffix = 'enduser';
        }
        if (response.rememberSFAToken) {
          CookiesHelper.setCookie(`rSFA-${rememberSFACookieSuffix}`, response.rememberSFAToken, 365);
        }
        this.router.navigateByUrl(this.sfaLoginDataService.nextPath).then(() => {
        });
      }, error: error => {
        this.loading = false;
        this.backendErrors = error.error;
        this.formErrors.setBackendErrors(error.error);
      }
    });
  }
}
