import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { of } from 'rxjs';
import { DomainApiService } from '@fleio-api/plugins/domains/domain-api.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { IDomainAvailabilityInfoModel } from '@fleio-api/plugins/domains/model/domain-availability-info.model';
import { OrderDomainApiService } from '@fleio-api/plugins/domains/order-domain-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { DomainUtils } from '@shared/plugins/utils/domain-utils';
import { IPriceCyclesModel } from '@fleio-api/plugins/domains/model/price-cycle.model';

@Component({
  selector: 'app-domain-transfer-form',
  templateUrl: './domain-transfer-form.component.html',
  styleUrls: ['./domain-transfer-form.component.scss']
})
export class DomainTransferFormComponent extends DetailsFormBase<IBaseFleioObjectModel> implements OnInit {
  newDomainForm = this.formBuilder.group({
    client: ['', Validators.required],
    name: ['', Validators.required],
    years: [0, Validators.required],
    epp: [''],
  });
  nameCtrl = this.newDomainForm.controls.name;

  checkingDomain: boolean;
  domainAvailability: IDomainAvailabilityInfoModel;
  domainUtils = new DomainUtils();
  prices: IPriceCyclesModel;

  preselectedDomainName = this.activatedRoute.snapshot.params.domain_name || null;
  preselectedClientId = this.activatedRoute.snapshot.params.client || null;

  constructor(
    private formBuilder: UntypedFormBuilder, private domainApiService: DomainApiService,
    private router: Router, public config: ConfigService, private activatedRoute: ActivatedRoute,
    private clientsApi: ClientsApiService,
    private orderDomainApiService: OrderDomainApiService,
    private notificationService: NotificationService,
  ) {
    super();
    if (this.preselectedClientId) {
      this.focusFirstInput = false;
    }
  }

  ngOnInit() {
    super.ngOnInit();

    if (this.preselectedDomainName) {
      this.newDomainForm.controls.name.setValue(this.preselectedDomainName);
    }

    if (this.preselectedClientId) {
      this.clientsApi.get(this.preselectedClientId).subscribe(client => {
        this.newDomainForm.controls.client.setValue(client);
      });
    }

    this.newDomainForm.controls.client.valueChanges.subscribe(() => {
      this.domainAvailability = null;
      if (this.preselectedDomainName && this.newDomainForm.controls.name.value === this.preselectedDomainName) {
        this.checkDomainName();
      }
    });
  }

  checkDomainName() {
    this.checkingDomain = true;
    this.objectController.loading = true;
    this.orderDomainApiService.isAvailableForTransfer(
      this.newDomainForm.controls.client.value.id,
      this.newDomainForm.controls.name.value,
    ).subscribe(
      domainAvailability => {
        this.domainAvailability = domainAvailability;
        if (domainAvailability.available) {
          this.prices = domainAvailability.premium_prices || domainAvailability.prices;
          if (!this.prices.transfer_adds_years) {
            this.newDomainForm.controls.years.setValue(0);
          }
          this.newDomainForm.controls.name.setValue(domainAvailability.adjusted_name);
          if (domainAvailability.tld.requires_epp_for_transfer) {
            this.newDomainForm.controls.epp.enable();
            this.newDomainForm.controls.epp.setValidators([Validators.required]);
          } else {
            this.newDomainForm.controls.epp.disable();
            this.newDomainForm.controls.epp.clearValidators();
          }
        }
      },
      () => {
        this.notificationService.showMessage($localize`Failed to check if domain is available for registration`);
        this.domainAvailability = {
          available: false,
          error: $localize`Error checking domain`
        };
      },
    ).add(() => {
      this.objectController.loading = false;
      this.checkingDomain = false;
    });
  }

  transferDomain(event?) {
    if (event) {
      event.preventDefault();
    }
    if (!this.domainAvailability || !this.domainAvailability.available) {
      return this.checkDomainName();
    }
    const domain = this.newDomainForm.value;
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }
    domain.client = domain.client.id;

    this.objectController.loading = true;
    this.orderDomainApiService.transferDomain(domain).subscribe(
      (order) => {
        this.notificationService.showMessage($localize`Domain transferred successfully`);
        this.router.navigateByUrl(this.config.getPanelUrl(`orders/${order.order_id}`));
      },
      () => {
        this.objectController.loading = false;
        this.notificationService.showMessage($localize`Failed to transfer domain`);
      }
    );
  }
}
