import { Component } from '@angular/core';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { SettingsApiService } from '@fleio-api/core/settings-api.service';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { IReferralSettingsModel } from '@fleio-api/core/model/referral-settings.model';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';
import { IProductModel } from '@fleio-api/billing/model/product.model';
import { ProductsApiService } from '@shared/fleio-api/billing/products/product-api.service';
import { EMPTY } from 'rxjs';
import { DetailsFormBase } from '@objects-view/details-form-base';

@Component({
  selector: 'app-referral-settings',
  templateUrl: './referral-settings.component.html',
  styleUrl: './referral-settings.component.scss'
})
export class ReferralSettingsComponent extends DetailsFormBase<IBaseFleioObjectModel> {
  referralSettingsForm = this.formBuilder.group({
    enable_referral_system: [false],
    referee_credit: [null, [ValidatorsHelper.requiredNumericValueValidator, Validators.min(0), ValidatorsHelper.nonZeroValidator]],
    referee_credit_valid_days: [null, [ValidatorsHelper.requiredIntegerValidator, Validators.min(1)]],
    referee_require_credit_card_on_signup: [false],
    referrer_credit: [null, [ValidatorsHelper.requiredNumericValueValidator, Validators.min(0), ValidatorsHelper.nonZeroValidator]],
    referee_spends_credit: [null, [ValidatorsHelper.requiredNumericValueValidator, Validators.min(0), ValidatorsHelper.nonZeroValidator]],
    referee_active_days: [null, [ValidatorsHelper.requiredIntegerValidator, Validators.min(1)]],
    limit_referee_credit_services: [false],
    referee_credit_services: [''],
  });
  loading = false;
  referralSettings: IReferralSettingsModel;
  products: Array<IProductModel>;

  constructor(
    private settingsApi: SettingsApiService,
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    public config: ConfigService,
    public productsApiService: ProductsApiService,
  ) {
    super();
  }

  ngOnInit(refreshTimerInterval?: number) {
    super.ngOnInit(refreshTimerInterval);
    this.productsApiService.list().subscribe({
      next: value => {
        this.products = value.objects;
      }
    });
    this.referralSettingsForm.controls.enable_referral_system.valueChanges.subscribe(value => {
      if (value) {
        this.referralSettingsForm.controls.referee_credit.enable();
        this.referralSettingsForm.controls.referee_credit_valid_days.enable();
        this.referralSettingsForm.controls.referee_require_credit_card_on_signup.enable()
        this.referralSettingsForm.controls.referrer_credit.enable();
        this.referralSettingsForm.controls.referee_spends_credit.enable();
        this.referralSettingsForm.controls.referee_active_days.enable();
        this.referralSettingsForm.controls.limit_referee_credit_services.enable();
        this.referralSettingsForm.controls.referee_credit_services.enable();
      } else {
        this.referralSettingsForm.controls.referee_credit.disable();
        this.referralSettingsForm.controls.referee_credit_valid_days.disable();
        this.referralSettingsForm.controls.referee_require_credit_card_on_signup.disable();
        this.referralSettingsForm.controls.referrer_credit.disable();
        this.referralSettingsForm.controls.referee_spends_credit.disable();
        this.referralSettingsForm.controls.referee_active_days.disable();
        this.referralSettingsForm.controls.limit_referee_credit_services.disable();
        this.referralSettingsForm.controls.referee_credit_services.disable();
      }
    });
    this.referralSettingsForm.controls.limit_referee_credit_services.valueChanges.subscribe(value => {
      if (value) {
        this.referralSettingsForm.controls.referee_credit_services.setValidators(Validators.required);
        this.referralSettingsForm.controls.referee_credit_services.updateValueAndValidity();
      } else {
        this.referralSettingsForm.controls.referee_credit_services.clearValidators();
        this.referralSettingsForm.controls.referee_credit_services.updateValueAndValidity();
      }
    })
  }

  protected initTabData() {
    this.loading = true;
    this.settingsApi.getReferralSettings().subscribe(referralSettings => {
      this.referralSettings = referralSettings;
      this.referralSettingsForm.patchValue(referralSettings);
      if (this.referralSettings.auto_order_service_id) {
        const refereeCreditServices = this.referralSettingsForm.controls.referee_credit_services.value;
        if (!refereeCreditServices || !refereeCreditServices.length) {
          this.referralSettingsForm.controls.referee_credit_services.setValue([this.referralSettings.auto_order_service_id]);
        }
      }
    }, error => {
      if (error.status === 403) {
        this.referralSettingsForm.disable();
      }
    }).add(() => {
      this.loading = false;
    });
  }

  saveSettings() {
    if (this.referralSettingsForm.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }
    const referralSettings = this.referralSettingsForm.value;
    this.objectController.loading = true;
    this.settingsApi.saveReferralSettings(referralSettings).subscribe(() => {
      this.notificationService.showMessage($localize`Referral settings saved`);
    }, () => {
      this.notificationService.showMessage($localize`Failed to save referral settings, check logs for details`);
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
