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 { DomainApiService } from '@fleio-api/plugins/domains/domain-api.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.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 { DomainUtils } from '@shared/plugins/utils/domain-utils';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IPluginComponent } from '@shared/plugins/interfaces/plugin-component';
import { of } from 'rxjs';
import { IPriceCyclesModel } from '@fleio-api/plugins/domains/model/price-cycle.model';
import { AuthService } from '@shared/auth/auth.service';

@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, IPluginComponent {
  public data: {
    domain_name: string;
  };
  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;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    public config: ConfigService,
    public authService: AuthService,
    private orderDomainApiService: OrderDomainApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit() {
    if (this.data?.domain_name) {
      // component is used without an objectController
      this.newDomainForm.controls.name.setValue(this.data.domain_name);
      this.ignoreObjectController = true;
    }
    super.ngOnInit();

    if (this.authService?.userData?.user?.clients) {
      this.newDomainForm.patchValue({
        client: this.authService.userData.user.clients[0],
      });
    }

    this.newDomainForm.controls.client.valueChanges.subscribe(() => {
      this.domainAvailability = null;
    });
  }

  checkDomainName() {
    this.checkingDomain = true;
    if (this.objectController) {
      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(() => {
      if (this.objectController) {
        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;

    if (this.objectController) {
      this.objectController.loading = true;
    }
    this.orderDomainApiService.transferDomain(domain, true).subscribe(
      () => {
        this.notificationService.showMessage($localize`Domain added to cart`);
        if (this.authService.feature('ui.staff')) {
          this.router.navigateByUrl(this.config.getPanelUrl(
            `orders/cart`
          )).then(() => {
          });
        } else {
          this.router.navigateByUrl(this.config.getPanelUrl(`billing/cart`));
        }
      },
      () => {
        if (this.objectController) {
          this.objectController.loading = false;
        }
        this.notificationService.showMessage($localize`Failed to transfer domain`);
      }
    );
  }
}
