import { Component, OnInit, Input, EventEmitter, Output, OnDestroy, ViewChild } from '@angular/core';
import { RemissionProduct, RemissionService } from '@isa/remission';
import { ModalService, ButtonComponent } from '@libs/ui';
import { filter, take, catchError, debounceTime, delay } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { NO_RESMISSION_REASON_SELECTED } from '../../constants/remission.constants';
import { RemissionHelperService } from '../../services/remission-helper.service';
import { Store } from '@ngxs/store';
import { SetRemissionIsLoading } from 'apps/sales/src/app/core/store/actions/remission.actions';

@Component({
  selector: 'app-add-product-to-remission-dialog',
  templateUrl: './add-product-to-remission-dialog.component.html',
  styleUrls: ['./add-product-to-remission-dialog.component.scss'],
})
export class AddProductToRemissionDialogComponent implements OnInit, OnDestroy {
  @ViewChild('addProductButton')
  addProductButton: ButtonComponent;

  id = 'remission-add-product-to-remission-modal';
  @Input() product: RemissionProduct;
  @Output() add = new EventEmitter<RemissionProduct>();
  @Output() closed = new EventEmitter();
  selectedFeatureDescription: string;
  toolTipOpened = false;
  tooltipMl = -10;
  tooltipArrowMl = 5;
  reasons: string[];
  reason: string;
  quantityRange = new Array(10).fill(0).map((_, index) => {
    if (index === 9) {
      return -1;
    }
    return index + 1;
  });
  quantity = 1;
  reasonError = false;
  reasonErrorMsg = 'Bitte wählen Sie einen Remigrund';
  constructor(
    private modalService: ModalService,
    private remissionService: RemissionService,
    private remissionHelper: RemissionHelperService,
    private store: Store
  ) {}

  ngOnInit() {
    this.subscriptions();
  }

  ngOnDestroy() {}

  subscriptions() {
    this.remissionService
      .getRemissionReasons()
      .pipe(
        filter((data) => !isNullOrUndefined(data)),
        take(1)
      )
      .subscribe((reasons) => {
        this.reasons = reasons;
        this.reason = NO_RESMISSION_REASON_SELECTED;
      });
  }

  public openDialog() {
    this.reason = NO_RESMISSION_REASON_SELECTED;
    this.quantity = 1;
    this.modalService.open(this.id);
  }

  closeDialog() {
    this.modalService.close(this.id);
    this.closed.emit();
  }

  addProduct() {
    this.modalService.close(this.id);
    this.add.emit(this.product);
  }

  openTooltip(desc: string, index: number) {
    if (index === 0) {
      this.tooltipMl = -10;
      this.tooltipArrowMl = 5;
    } else {
      const offsetConstant = 37;
      const offset = offsetConstant * index;
      this.tooltipMl = -10 + offset;
      this.tooltipArrowMl = 5 + offset;
    }
    this.selectedFeatureDescription = desc;
    this.toolTipOpened = true;
  }

  closeTooltip() {
    this.toolTipOpened = false;
  }

  quantityUpdated(quantity: number) {
    this.quantity = quantity;
  }

  reasonUpdated(reason: string) {
    this.reason = reason;
    this.reasonError = false;
  }

  isArray(obj) {
    return Array.isArray(obj);
  }

  addProdcutToList() {
    if (this.reason === NO_RESMISSION_REASON_SELECTED) {
      this.reasonError = true;
      return;
    }

    this.store.dispatch(new SetRemissionIsLoading(true));
    this.addProductButton.startLoading();

    this.remissionService
      .addProductToRemit({
        product: this.product,
        remissionReason: this.reason,
        remissionQuantity: this.quantity,
      })
      .pipe(
        catchError((err) => {
          this.store.dispatch(new SetRemissionIsLoading(false));
          this.addProductButton.stopLoading();
          return [err];
        }),
        debounceTime(250),
        take(1),
        delay(2000)
      )
      .subscribe((product: RemissionProduct) => {
        this.reasonError = false;
        this.remissionHelper.addRemissionListItem(product);
        this.modalService.close(this.id);
        this.add.emit(product);
      });
  }
}
