import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IZoneModel } from '@fleio-api/openstack/zone/model/zone.model';
import { IZoneCreateOptionsModel } from '@fleio-api/openstack/zone/model/zone-create-options.model';
import { ZonesApiService } from '@fleio-api/openstack/zone/zones-api.service';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-zone-edit-form',
  templateUrl: './zone-edit-form.component.html',
  styleUrls: ['./zone-edit-form.component.scss']
})
export class ZoneEditFormComponent extends DetailsFormBase<IZoneModel> implements OnInit {
  zoneForm = this.formBuilder.group({
    name: ['', Validators.required],
    email: ['', Validators.required],
    description: [''],
    ttl: [1800],
    ip_address: [''],
  });
  loading = false;
  estimatedCost: string;
  estimatedCostLoading = false;

  createOptions: IZoneCreateOptionsModel;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private zonesApiService: ZonesApiService,
    private router: Router,
    private config: ConfigService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.zoneActions();
      this.createOptions = this.objectController.additionalObjects.createOptions;
    }

    if (this.object && this.object.id) {
      this.zoneForm.patchValue(this.object);
      this.zoneForm.controls.name.disable();
    }

    this.zoneForm.valueChanges.pipe(debounceTime(300)).subscribe(() => {
      this.getSimulatedPrice();
    });
  }

  zoneActions(): Observable<IActionResult> {
    const value = this.zoneForm.value as IZoneModel;

    this.loading = true;
    this.createOrUpdate(
      this.zonesApiService,
      value,
    ).subscribe(() => {
      this.redirectAfterCreate('openstack/zones', this.router, this.config);
      this.notificationService.showMessage($localize`Zone saved`);
    }).add(() => {
      this.loading = false;
    });
    return of(null);
  }

  getSimulatedPrice() {
    if (this.authSvc.feature('openstack.dns.zones.show-price-on-create')) {
      const zone = this.zoneForm.value;
      if (zone.ttl && zone.email) {
        const params = {
          email: zone.email,
          ttl: zone.ttl,
        } as any;
        this.estimatedCostLoading = true;
        this.zonesApiService.getPrice(params).subscribe({
          next: response => {
            this.estimatedCost = response.estimated_cost_display;
          },
          error: error => {
            if (error?.error?.detail) {
              if (this.config.authService.feature('ui.staff')) {
                this.estimatedCost = error.error.detail;
              } else {
                this.estimatedCost = null;
              }
            }
          }
        }).add(() => {
          this.estimatedCostLoading = false;
        });
      }
    }
  }
}
