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 { of } from 'rxjs';
import { CookiesHelper } from '@shared/ui-api/helpers/cookies-helper';
import { ThemingService } from '@shared/ui/theming/theming.service';

@Component({
  selector: 'app-google-authenticator-confirm-form',
  templateUrl: './google-authenticator-confirm-form.component.html',
  styleUrls: ['./google-authenticator-confirm-form.component.scss']
})
export class GoogleAuthenticatorConfirmFormComponent implements OnInit {
  confirmLoginForm = this.formBuilder.group({
    code: ['', [Validators.required, Validators.pattern('[0-9]*')]],
    rememberSFA: [false]
  });
  logoLinkOptions = new LogoLinkOptions(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 themingService: ThemingService,
  ) {
  }

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

  ngOnInit() {
    if (!this.sfaLoginDataService.email) {
      this.router.navigateByUrl(this.config.getPanelUrl('login'));
    }
    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: 'google_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);
      }
    });
  }
}
