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 { IActionResult } from '@objects-view/interfaces/actions/action-result';
import {
  IServiceCycleModel,
  ServiceCycleBillingTypes,
  ServiceCycleStates,
  ServiceCycleTypes
} from '@fleio-api/billing/service-cycles/models/service-cycle-model';
import { ServiceCyclesApiService } from '@fleio-api/billing/service-cycles/service-cycles-api.service';
import { ServiceCycleEditTrackerService } from '../../service-cycle-edit-tracker.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { ConfigService } from '@shared/config/config.service';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-service-cycle-edit-form',
  templateUrl: './service-cycle-edit-form.component.html',
  styleUrls: ['./service-cycle-edit-form.component.scss']
})
export class ServiceCycleEditFormComponent extends DetailsFormBase<IServiceCycleModel> implements OnInit {
  serviceCycleForm = this.formBuilder.group({
    state: ['', Validators.required],
    price: ['', [Validators.min(0), ValidatorsHelper.requiredNumericValueValidator]],
    standard_price: ['', [Validators.min(0), ValidatorsHelper.requiredNumericValueValidator]],
    fixed_price: ['', [Validators.min(0), ValidatorsHelper.requiredNumericValueValidator]],
    dynamic_price: ['', [Validators.min(0), ValidatorsHelper.requiredNumericValueValidator]],
    start_dt: [''],
    end_dt: [''],
    price_override: [''],
    price_override_model: [''],
  });

  ServiceCycleStates = ServiceCycleStates;
  ServiceCycleTypes = ServiceCycleTypes;
  ServiceCycleBillingTypes = ServiceCycleBillingTypes;
  datePipe: DateFormatterPipe;

  constructor(
    private config: ConfigService,
    private formBuilder: UntypedFormBuilder,
    private serviceCyclesApiService: ServiceCyclesApiService,
    private serviceCycleEditTrackerService: ServiceCycleEditTrackerService,
  ) {
    super();
    this.datePipe = new DateFormatterPipe(this.config);
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.serviceCycleActions();
    }
    this.serviceCycleForm.controls.price_override.valueChanges.subscribe(priceOverride => {
      if (priceOverride) {
        this.serviceCycleForm.controls.price_override_model.enable();
      } else {
        this.serviceCycleForm.controls.price_override_model.disable();
      }
    });

    if (this.object?.id) {
      this.serviceCycleForm.patchValue(this.object);
    }
    if (this.object.start_dt) {
      this.serviceCycleForm.controls.start_dt.setValue(
        new Date(this.datePipe.getDate(this.object.start_dt))
      );
    }

    if (this.object.end_dt) {
      this.serviceCycleForm.controls.end_dt.setValue(
        new Date(this.datePipe.getDate(this.object.end_dt))
      );
    }
  }

  serviceCycleActions(): Observable<IActionResult> {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }
    const value = this.serviceCycleForm.value as IServiceCycleModel;

    if (!value.price_override) {
      value.price_override_model = 'none';
    }

    return new Observable<IActionResult>(subscriber => {
      let startDTWithoutOffset = new Date(value.start_dt.setMinutes(value.start_dt.getMinutes() - value.start_dt.getTimezoneOffset()));
      let endDTWithoutOffset = new Date(value.end_dt.setMinutes(value.end_dt.getMinutes() - value.end_dt.getTimezoneOffset()));
      (value as any).start_date = startDTWithoutOffset.toISOString().split('T')[0];
      (value as any).end_date = endDTWithoutOffset.toISOString().split('T')[0];
      this.createOrUpdate(
        this.serviceCyclesApiService,
        value,
        true
      ).subscribe({
        next: () => {
          if (value.id) {
            this.serviceCycleEditTrackerService.editedServiceCycle(value.id);
          }
          subscriber.next({success: true, message: $localize`Service cycle saved`});
        },
        error: () => {
          subscriber.next({success: false, message: $localize`Failed to save service cycle`});
        }
      }).add(() => {
        subscriber.complete();
      });
    });
  }
}
