import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IDomainModel } from '@fleio-api/plugins/domains/model/domain.model';
import { ConfigService } from '@shared/config/config.service';
import { IDomainRegistrarModel } from '@fleio-api/plugins/domains/model/domain-registrar.model';
import { UntypedFormBuilder } from '@angular/forms';
import { DomainApiService } from '@fleio-api/plugins/domains/domain-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IDomainInfoModel } from '@fleio-api/plugins/domains/model/domain-info.model';
import { IDomainActionResultModel } from '@fleio-api/plugins/domains/model/domain-action-result.model';
import * as _moment from 'moment';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-domain-details-overview',
  templateUrl: './domain-details-overview.component.html',
  styleUrls: ['./domain-details-overview.component.scss']
})
export class DomainDetailsOverviewComponent extends DetailsComponentBase<IDomainModel> implements OnInit {
  registrarFrom = this.formBuilder.group({
    registrar: [''],
  });

  domainInfo: IDomainInfoModel;
  actionIsRunning: boolean;
  actionStatusMessage: string;
  actionSucceeded: boolean;
  domainRegistrars: IDomainRegistrarModel[];

  constructor(
    private formBuilder: UntypedFormBuilder,
    public config: ConfigService,
    private domainsApiService: DomainApiService,
    private notificationService: NotificationService,
    private refreshService: RefreshService,
    private activatedRoute: ActivatedRoute,
  ) {
    super();
  }


  ngOnInit() {
    super.ngOnInit();
    this.domainRegistrars = this.activatedRoute.snapshot.data['registrars']?.objects;

    if (this.object) {
      this.registrarFrom.controls.registrar.setValue(
        this.object.last_registrar
      );
    }

    this.refreshDomainInfo();

    this.registrarFrom.controls.registrar.valueChanges.subscribe(() => {
      this.refreshDomainInfo();
    });
  }

  refreshDomainInfo() {
    if (this.registrarFrom.controls.registrar.value) {
      this.domainsApiService.getInfo(
        this.object.id, this.registrarFrom.controls.registrar.value,
      ).subscribe(
        domainInfo => {
          this.domainInfo = domainInfo;
        }
      );
    } else {
      this.domainInfo = undefined;
    }
  }

  saveRegistrar() {
    this.object.last_registrar = this.registrarFrom.controls.registrar.value;
    this.domainsApiService.update(this.object.id, this.object).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Registrar saved successfully`);
        this.refreshDomainInfo();
      },
      error: () => {
        this.notificationService.showMessage($localize`Failed to save registrar`);
      }
    });
  }

  executeAction(name: string, displayName: string) {
    if (this.actionIsRunning) {
      return;
    }
    let importantMessage = null;
    if (name === 'renew' && this.object.latest_renew_at) {
      const datePipe = new DateFormatterPipe(this.config);
      // @ts-ignore
      const diffTime = new Date().getTime() - new Date(this.object.latest_renew_at).getTime();
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
      if (diffDays <= 365) {
        importantMessage = $localize`This domain was already renewed ${_moment.duration(diffTime).humanize()} ago up until ${datePipe.transform(this.object.expiry_date)}`;
      }
    }
    this.notificationService.confirmDialog({
      message: $localize`Are you sure you want to execute ${displayName} action?`,
      title: $localize`Execute ${displayName} action`,
      importantMessage,
    }).subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.actionIsRunning = true;
        this.actionStatusMessage = undefined;
        this.domainsApiService.executeAction(
          this.object.id, name, this.registrarFrom.controls.registrar.value,
        ).subscribe(
          {
            next: actionResult => {
              this.actionStatusMessage = actionResult.action_status_message;
              this.actionSucceeded = actionResult.action_status;
              this.notificationService.showMessage(actionResult.details);
              this.refreshService.refresh();
            }
            ,
            error: error => {
              const actionResult = error.error as IDomainActionResultModel;
              this.actionStatusMessage = actionResult.action_status_message;
              this.actionSucceeded = actionResult.action_status;
              this.notificationService.showMessage(actionResult.details);
            }
          }
        ).add(() => {
          this.actionIsRunning = false;
        });
      }
    });
  }
}
