import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { UntypedFormControl, UntypedFormGroup, ValidationErrors } from '@angular/forms';
import { RemissionPlacementType } from '@domain/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,
  standalone: false,
})
export class AddProductToShippingDocumentModalComponent implements OnInit {
  validateQuantity(c: UntypedFormControl): 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: UntypedFormGroup;

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

  ngOnInit() {
    this.form = new UntypedFormGroup({
      placementType: new UntypedFormControl(this._modalRef?.data?.item?.placementType ?? ''),
      quantity: new UntypedFormControl(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,
      });
    }
  }
}
