import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { RemissionPlacementType } from '@isa/remission';
import { UiModalRef } from '@ui/modal';

@Component({
  selector: 'page-add-product-to-shipping-document-modal',
  templateUrl: 'add-product-to-shipping-document-modal.component.html',
  styleUrls: ['add-product-to-shipping-document-modal.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AddProductToShippingDocumentModalComponent implements OnInit {
  validateQuantity(c: FormControl): ValidationErrors | null {
    if (!c.value) {
      return { invalid: 'Menge wird benötigt' };
    }
    return c.value < 1 || c.value > 1000 ? { invalid: 'Menge ist ungültig' } : null;
  }

  remissionPlacementTypes: RemissionPlacementType[] = ['Stapel', 'Leistung'];
  form: FormGroup;

  constructor(private _modalRef: UiModalRef<{ action: string; quantity?: number; placementType?: RemissionPlacementType }>) {}

  ngOnInit() {
    this.form = new FormGroup({
      placementType: new FormControl(this._modalRef?.data?.item?.placementType ?? ''),
      quantity: new FormControl(1, [this.validateQuantity]),
    });
  }

  async notFound() {
    this._modalRef.close({ action: 'notFound' });
  }

  async remit() {
    if (this.form.value.quantity == 0) {
      this.notFound();
    } else {
      this._modalRef.close({ action: 'remit', quantity: this.form.value.quantity, placementType: this.form.value.placementType });
    }
  }
}
