import { Component, OnInit, ViewChild } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { CoreApiService } from '@fleio-api/core/core-api.service';

@Component({
  selector: 'app-confirm-email-form',
  templateUrl: './confirm-email-form.component.html',
  styleUrls: ['./confirm-email-form.component.scss']
})
export class ConfirmEmailFormComponent extends DetailsFormBase<any> implements OnInit {
  @ViewChild('formErrors') formErrors;
  confirmEmailForm = this.formBuilder.group({
    confirmation_code: ['', Validators.required]
  });
  resendMessage = null;
  formGroup = this.confirmEmailForm;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    public config: ConfigService,
    private notificationService: NotificationService,
    private coreApiService: CoreApiService,
    private activatedRoute: ActivatedRoute,
  ) {
    super();
  }

  confirmEmail(): Observable<IActionResult> {
    const value = this.confirmEmailForm.value;
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }

    this.objectController.loading = true;
    this.coreApiService.confirmEmail(
      value.confirmation_code
    ).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Email successfully confirmed`);
        this.router.navigateByUrl(this.config.getPanelHomeUrl()).then(() => {
        });
      },
      error: (error) => {
        if (error?.status === 409) {
          this.notificationService.showMessage($localize`Email already confirmed!`);
          this.router.navigateByUrl(this.config.getPanelHomeUrl()).then(() => {
          });
        } else {
          this.objectController.loading = false;
          if (error.error) {
            this.setErrors(error.error);
            return of(null);
          } else {
            throw error;
          }
        }
      }
    });
    return of(null);
  }

  resendCode() {
    this.notificationService.confirmDialog(
      {
        title: $localize`Resend confirmation code`,
        message: $localize`Are you sure you want to resend confirmation code?`
      }
    ).subscribe({
      next: (result) => {
        if (result?.button === 'yes') {
          this.coreApiService.resendEmailConfirmationMessage().subscribe({
            next: (response) => {
              this.resendMessage = response.detail;
            },
            error: (error) => {
              if (error?.status === 409) {
                this.notificationService.showMessage($localize`Email already confirmed!`);
                this.router.navigateByUrl(this.config.getPanelHomeUrl()).then(() => {
                });
              } else {
                this.notificationService.showMessage($localize`Could not resend confirmation code.`);
              }
            }
          });
        }
      },
      error: () => {
        this.notificationService.showMessage($localize`Could not resend confirmation code.`);
      }
    });
  }

  ngOnInit(): void {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.confirmEmail();
    }
    this.activatedRoute.params.subscribe(value => {
      if (value && value.token) {
        this.confirmEmailForm.controls.confirmation_code.setValue(value.token);
        this.confirmEmail();
      }
    });
  }

}
