import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { DomainRemissionService } from '@domain/remission';
import { ReceiptItemDTO, ReturnDTO } from '@swagger/remi';
import { UiErrorModalComponent, UiMessageModalComponent, UiModalService } from '@ui/modal';

@Component({
  selector: 'page-shared-shipping-document-details',
  templateUrl: 'shipping-document-details.component.html',
  styleUrls: ['shipping-document-details.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SharedShippingDocumentDetailsComponent {
  @Input()
  return: ReturnDTO;

  @Input()
  canRemoveItems: boolean = false;

  @Input()
  loading: boolean = false;

  @Input()
  showAddToRemiHint: boolean = false;

  @Output()
  deleted = new EventEmitter<ReturnDTO>();

  @Output()
  itemDeleted = new EventEmitter<ReceiptItemDTO>();

  get firstReceipt() {
    return this.return.receipts?.find((_) => true)?.data;
  }

  get completed() {
    return !!this.return.completed;
  }

  get itemsCount() {
    return this.firstReceipt?.items?.length ?? 0;
  }

  get firstReceiptPackageNumber() {
    return this.firstReceipt?.packages?.find((_) => true)?.data?.packageNumber;
  }

  constructor(private _remissionService: DomainRemissionService, private _modal: UiModalService) {}

  async deleteReturn() {
    if (this.itemsCount > 0) {
      const modal = this._modal.open({
        content: UiMessageModalComponent,
        title: 'Warenbegleitschein löschen',
        data: {
          message:
            'Mit Abbrechen der Remission werden alle Titel vom\nWarenbegleitschein entfernt und die Remission beendet. Entnehmen\nSie die Artikel auch physisch aus der Wanne.',
          closeAction: 'Erledigt',
        },
      });
      const result = await modal.afterClosed$.toPromise();
      if (!result.data) return;
    }

    try {
      await this._remissionService.deleteReturn(this.return.id);
      this.deleted.emit(this.return);
    } catch (err) {
      this._modal.open({ content: UiErrorModalComponent, title: 'Fehler beim Löschen des Warenbegleitscheins', data: err });
    }
  }

  async removeItem(item: ReceiptItemDTO) {
    try {
      this.loading = true;
      const response = await this._remissionService
        .removeReturnItemFromReceipt({
          returnId: this.return.id,
          receiptId: this.firstReceipt.id,
          receiptItemId: item.id,
        })
        .toPromise();
      this.loading = false;
      if (!!response && !response?.error && Object.keys(response?.result)?.length > 0) {
        this.firstReceipt.items = this.firstReceipt.items.filter((i) => i.id !== item.id);
        this.itemDeleted.emit(item);
      } else {
        throw new Error('Keine Response vorhanden');
      }
    } catch (err) {
      this.loading = false;
      this._modal.open({ content: UiErrorModalComponent, title: 'Fehler beim Löschen des Artikels', data: err });
    }
  }
}
