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 { IClientModel } from '@fleio-api/client-user/model/client.model';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { debounceTime } from 'rxjs/operators';
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 { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@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({
    client: ['', Validators.required],
    name: ['', Validators.required],
    email: ['', Validators.required],
    type_: ['', Validators.required],
    description: [''],
    ttl: [1800, ValidatorsHelper.requiredIntegerValidator],
    ip_address: [''],
  });
  createInClientProject = true;
  clientControl = this.zoneForm.controls.client;
  estimatedCost: string;
  estimatedCostLoading = false;

  createOptions: IZoneCreateOptionsModel;

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

  changeDestination(value) {
    // createInClientProject
    if (value === false) {
      this.clientControl.setValue('');
      this.clientControl.clearValidators();
      this.clientControl.reset();
    } else {
      this.clientControl.setValidators(Validators.required);
    }
    this.estimatedCost = null;
  }


  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.client.disable();
      this.zoneForm.controls.name.disable();
      this.zoneForm.controls.type_.disable();
    }

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

  zoneActions(): Observable<IActionResult> {
    const value = this.zoneForm.value as any;
    if (this.object.id) {
      value.type = this.object.type;
    }

    if (value.client && (value.client as IClientModel).id) {
      value.client = (value.client as IClientModel).id;
    }

    if (!this.object.id && !this.createInClientProject) {
      value.create_as_admin = true;
    }

    this.createOrUpdate(
      this.zonesApiService,
      value,
    ).subscribe(() => {
      this.redirectAfterCreate('openstack/zones', this.router, this.config);
      this.notificationService.showMessage($localize`Zone saved`);
    });
    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 && zone?.client?.id) {
        const params = {
          email: zone.email,
          ttl: zone.ttl,
          client_id: zone.client.id,
        } 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;
        });
      }
    }
  }
}
