import { AfterViewInit, Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { LogoLinkOptions } from '@shared/ui/logo/logo.component';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { of } from 'rxjs';
import { ThemingService } from '@shared/ui/theming/theming.service';
import { CookiesHelper } from '@shared/ui-api/helpers/cookies-helper';
import { ReferralInfoApiService } from '@fleio-api/core/referral-info-api.service';
import { AuthService } from '@shared/auth/auth.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent extends DetailsFormBase<any> implements OnInit, AfterViewInit {
  @ViewChild('captchaRef2') captchaRef2: ElementRef;
  private reCaptchaRendered = false;
  reCaptchaValid = false;
  reCaptchaToken: string;
  grecaptcha: any;
  signupForm = this.formBuilder.group({
    first_name: ['', Validators.required],
    last_name: ['', Validators.required],
    email: ['', Validators.required],
    password: ['', Validators.required],
    rememberMe: [false],
    invitation_id: [null],
    invitation_token: [null],
  });
  passwordCtrl = this.signupForm.controls.password;
  logoLinkOptions = new LogoLinkOptions(false);
  nextUrl;
  cardTopMargin: string;
  loading: boolean;
  referralInfo = null;

  @ViewChild('formErrors') formErrors;
  formGroup = this.signupForm;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    public config: ConfigService,
    private themingService: ThemingService,
    private referralInfoApiService: ReferralInfoApiService,
    public auth: AuthService,
  ) {
    super();
  }

  reCaptchaSuccess(data: any){
    if (data) {
      this.reCaptchaValid = true;
      this.reCaptchaToken = data;
    }
  }

  reCaptchaExpired(){
    this.reCaptchaValid = false;
  }

  ngAfterViewInit() {
    super.ngAfterViewInit();
    this.grecaptcha = (window as any).grecaptcha;
    if (this.grecaptcha && this.config.current.settings.reCaptchaSiteKey) {
      this.grecaptcha.render(this.captchaRef2.nativeElement, {
        sitekey: this.config.current.settings.reCaptchaSiteKey,
        callback: (response) => this.reCaptchaSuccess(response),
        'expired-callback': () => this.reCaptchaExpired()
      });
      this.reCaptchaRendered = true;
    }
  }

  ngOnInit() {
    if (this.config.authService && this.config.authService.userData &&
      this.config.authService.userData.requires_tos_agreement) {
      this.signupForm.addControl('tos_agreement', this.formBuilder.control(false));
    }
    this.nextUrl = this.config.getPanelUrl('clients/create');
    this.activatedRoute.params.subscribe(value => {
      if (value && value.invitationId && value.invitationToken) {
        this.nextUrl = this.config.getPanelUrl('clients');
        this.signupForm.controls.invitation_id.setValue(value.invitationId);
        this.signupForm.controls.invitation_token.setValue(value.invitationToken);
      }
      if (value && value.email) {
        this.signupForm.controls.email.setValue(value.email);
      }
    });
    const queryParams = this.activatedRoute.snapshot.queryParams;
    if (queryParams.ref) {
      if (this.config.enduser.settings.referralCookieDays) {
        CookiesHelper.setCookie(`referralCode`, queryParams.ref, this.config.enduser.settings.referralCookieDays);
      } else {
        this.nextUrl = this.config.getPanelUrl(`clients/create?ref=${queryParams.ref}`);
      }
      this.referralInfoApiService.getInfo(queryParams.ref).subscribe(value => {
        if (value.referee_credit) {
          this.referralInfo = value;
        }
      });
    }
    this.setCardTopMargin(window.innerHeight);
  }

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

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

  signup() {
    if (this.reCaptchaRendered && !this.reCaptchaValid) {
      return of(null);
    }
    const value = this.signupForm.value;
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }

    if (this.reCaptchaRendered && this.reCaptchaValid && this.reCaptchaToken) {
      value.captcha_token = this.reCaptchaToken;
    }
    this.loading = true;
    this.config.authService.signup(
      value
    ).subscribe({
      next: (result: any) => {
        if (result.success) {
          this.config.authService.checkIfLoggedIn().subscribe(() => {
            this.config.authService.signalLoginCompleted();
            this.router.navigateByUrl(this.nextUrl).then(() => {
            });
          });
        } else {
          this.loading = false;
          if (this.grecaptcha && this.reCaptchaRendered) {
            this.grecaptcha.reset();
            this.reCaptchaValid = false;
          }
          this.setErrors(result.error.error);
        }
      },
      error: () => {
        this.loading = false;
      }
    });
  }
}
