import { Component, HostListener, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { LogoLinkOptions } from '../../ui/logo/logo.component';
import { FormErrorsComponent } from '../../error-handling/form-errors/form-errors.component';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from '../auth.service';
import { ConfigService } from '../../config/config.service';
import { of } from 'rxjs';
import { ThemingService } from '@shared/ui/theming/theming.service';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IObjectController } from '@objects-view/interfaces/object-controller';
import { StaticObjectController } from '@objects-view/static-object-controller';

@Component({
  selector: 'app-new-password',
  templateUrl: './new-password.component.html',
  styleUrls: ['./new-password.component.scss']
})
export class NewPasswordComponent extends DetailsFormBase<any> implements OnInit {
  newPassForm = this.formBuilder.group({
    new_password: ['', Validators.required],
    confirm_password: ['', Validators.required],
    user_id: ['', Validators.required],
    token: ['', Validators.required],
  });
  newPasswordCtrl = this.newPassForm.controls.new_password;
  confirmPasswordCtrl = this.newPassForm.controls.confirm_password;
  logoLinkOptions = new LogoLinkOptions(false);
  resetRequested = false;
  cardTopMargin: string;
  stateParams: {
    userid?: any;
    token?: any;
  };
  loading: boolean;

  @ViewChild('formErrors') formErrors: FormErrorsComponent;

  public objectController: IObjectController = new StaticObjectController(null);


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

  ngOnInit() {
    super.ngOnInit();
    this.stateParams = this.activatedRoute.snapshot.params;
    this.newPassForm.controls.user_id.setValue(this.stateParams.userid);
    this.newPassForm.controls.token.setValue(this.stateParams.token);
    this.setCardTopMargin(window.innerHeight);
  }

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

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

  submit() {
    this.validate();
    if (this.newPassForm.invalid) {
      return of(null);
    }
    const value = this.newPassForm.value;
    this.loading = true;
    this.auth.setNewPassword(
      value
    ).subscribe({
      next: () => {
        this.resetRequested = true;
      }, error: error => {
        this.setErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
