import { Component, OnInit, ViewChild } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { Router } from '@angular/router';
import { EMPTY, of } from 'rxjs';
import { SmsAuthenticatorApiService } from '@fleio-api/plugins/sms-authenticator/sms-authenticator-api.service';
import { UserProfileApiService } from '@fleio-api/profile/user-profile/user-profile-api.service';
import { IUserProfileDataModel } from '@shared/auth/models/user.model';
import { CartUtilsService } from '@fleio-api/billing/cart/cart-utils.service';
import { AuthService } from '@shared/auth/auth.service';

@Component({
  selector: 'app-sms-authenticator-details-tab',
  templateUrl: './sms-authenticator-details-tab.component.html',
  styleUrls: ['./sms-authenticator-details-tab.component.scss']
})
export class SmsAuthenticatorDetailsTabComponent extends DetailsFormBase<any> implements OnInit {
  smsForm = this.formBuilder.group({
    code: ['', [Validators.required, Validators.pattern('[0-9]*')]]
  });
  profileForm = this.formBuilder.group({
    phone: [''],
  });
  userProfile: IUserProfileDataModel;
  status: {
    enabled: boolean;
    default: boolean;
  };
  loading = false;
  constructor(
    private smsAuthenticatorApiService: SmsAuthenticatorApiService,
    public config: ConfigService,
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    private userProfileApiService: UserProfileApiService,
    private cartUtilsService: CartUtilsService,
    private authService: AuthService,
  ) {
    super();
  }

  getSMSData() {
    this.loading = true;
    this.smsAuthenticatorApiService.getStatus().subscribe(response => {
      this.status = response;
      this.loading = false;
      this.userProfileApiService.getProfile().subscribe(value => {
        this.userProfile = value.user;
        const phoneNumber = JSON.parse(JSON.stringify(this.userProfile.mobile_phone_number));
        if (!phoneNumber) {
          this.smsForm.controls.code.disable();
        } else {
          if (this.smsForm.controls.code.disabled) {
            this.smsForm.controls.code.enable();
          }
        }
      });
    }, error => {
      if (error.status === 403) {
        this.notificationService.showMessage('You need to confirm password');
        this.router.navigateByUrl(this.config.getPanelUrl('sfa/confirm-password'));
        this.loading = false;
      } else {
        this.notificationService.showMessage($localize`Failed to get second factor auth method status`);
        this.loading = false;
      }
    });
  }

  ngOnInit(): void {
    this.getSMSData();
  }

  savePhone() {
    const phone = this.profileForm.controls.phone.value;
    if (!phone) {
      this.notificationService.showMessage($localize`Please enter phone number`);
      return of(null);
    }
    const value = JSON.parse(JSON.stringify(this.userProfile)); // deep copy
    value.mobile_phone_number = phone;
    this.userProfileApiService.putAction(
      'update',
      value
    ).subscribe(response => {
      this.notificationService.showMessage($localize`User profile updated.`);
      this.getSMSData();
    }, error => {
      this.backendErrors = error.error;
      if (this.backendErrors.mobile_phone_number) {
        this.notificationService.showMessage(this.backendErrors.mobile_phone_number);
      }
    });
  }

  requestCode() {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Send code?`,
      message: $localize`You will receive a new code on your mobile phone number (${this.userProfile.mobile_phone_number}). Go to your profile to change your phone number.`
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.smsAuthenticatorApiService.sendCode().subscribe(response => {
          this.getSMSData();
        }, error => {
          this.notificationService.showMessage($localize`Failed to send code.`);
        });
      }
    });
  }

  enable() {
    this.validate();
    if (this.smsForm.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    const value = this.smsForm.value;

    this.loading = true;
    this.smsAuthenticatorApiService.enable(value.code).subscribe(response => {
      this.getSMSData();
      if (this.authService.feature('ui.enduser') && this.cartUtilsService.redirectToCart) {
        this.router.navigateByUrl(this.config.getPanelUrl(`billing/cart`)).then(()=>{});
      }
    }, error => {
      if (error.error) {
        this.setErrors(error.error);
      }
      this.getSMSData();
    });
  }

  disable() {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Disable SMS verification?`,
      message: $localize`Are you sure?`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.smsAuthenticatorApiService.disable().subscribe(response => {
          this.getSMSData();
        }, error => {
          this.notificationService.showMessage($localize`Failed to disable second factor auth method.`);
        });
      }
    });
  }

  makeDefault() {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Set SMS verification as default`,
      message: $localize`Are you sure?`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.smsAuthenticatorApiService.makeDefault().subscribe(response => {
          this.getSMSData();
        }, error => {
          this.notificationService.showMessage(
            $localize`Failed to make SMS verification the default second factor auth method.`
          );
        });
      }
    });
  }

}
