import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { DomainRemissionService } from '@domain/remission';
import { DialogModel, UiDialogModalComponent, UiModalService } from '@ui/modal';
import { UiSearchboxNextComponent } from '@ui/searchbox';
import { Subject } from 'rxjs';
import { first, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'page-finish-shipping-document',
  templateUrl: 'finish-shipping-document.component.html',
  styleUrls: ['finish-shipping-document.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class FinishShippingDocumentComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject<void>();

  @ViewChild(UiSearchboxNextComponent)
  searchboxComponent: UiSearchboxNextComponent;

  loading$ = new Subject<boolean>();

  hint$ = new Subject<string>();

  get supplierId(): number {
    return Number(this._activatedRoute?.snapshot?.queryParams?.supplier);
  }

  get source(): string {
    return this._activatedRoute?.snapshot?.queryParams?.source;
  }

  get returnId(): number {
    return Number(this._activatedRoute?.snapshot?.params?.returnId);
  }

  get receiptId(): number {
    return Number(this._activatedRoute?.snapshot?.params?.receiptId);
  }

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _modal: UiModalService,
    private _router: Router,
    private _breadcrumb: BreadcrumbService,
    private _config: Config,
    private _remissionService: DomainRemissionService,
  ) {}

  ngOnInit() {
    this.addBreadcrumbIfNotExists();
  }

  ngOnDestroy(): void {
    this._onDestroy$.next();
    this._onDestroy$.complete();
  }

  clearHint() {
    this.hint$.next('');
  }

  search(query: string) {
    query = query?.trim();
    if (!query) {
      this.hint$.next('Ungültige Eingabe');
      return;
    }

    if (query.length !== 14) {
      this.hint$.next('14 Zeichen benötigt');
      return;
    }

    const modal = this._modal.open({
      content: UiDialogModalComponent,
      title: `Ist die Wannenummer korrekt oder möchten Sie die\nWannenummer erneut scannen?\n\n${query}`,
      data: {
        handleCommand: false,
        actions: [
          { label: 'Erneut scannen', command: 'rescan' },
          { label: 'Nummer korrekt', selected: true, command: 'correct' },
        ],
      } as DialogModel,
    });

    modal.afterClosed$.pipe(takeUntil(this._onDestroy$)).subscribe(async (result) => {
      if (result?.data === 'correct') {
        try {
          await this.createReceiptAndAssignPackageNumber(query);

          if (coerceBooleanProperty(this._activatedRoute.snapshot.queryParams?.complete)) {
            this._router.navigate(['/filiale', 'remission', this.returnId, 'shipping-document'], {
              queryParams: { complete: true },
            });
          } else {
            await this.navigateToRemissionList(query);
          }
        } catch (error) {}
      } else if (result?.data === 'rescan') {
        this.searchboxComponent.clear();
      }
    });
  }

  async navigateToRemissionList(packageNumber: string) {
    await this._router.navigate(['/filiale', 'remission', this.returnId, packageNumber, 'list'], {
      queryParams: { ...this._activatedRoute.snapshot.queryParams, supplier: this.supplierId, source: this.source },
    });
  }

  async createReceiptAndAssignPackageNumber(packageNumber: string) {
    const returnDTO = await this._remissionService.getReturn(this.returnId).pipe(first()).toPromise();
    // const receipt = await this._remissionService.createReceipt(returnDTO, this.receiptId);
    try {
      return await this._remissionService.createReceiptAndAssignPackage({
        returnId: returnDTO.id,
        receiptId: this.receiptId,
        packageNumber,
      });
    } catch (error) {
      this._modal.error('Fehler beim Speichern der Wannennummer', error).afterClosed$.subscribe(() => {
        this._router.navigate(['/filiale', 'remission', this.returnId, 'finish-shipping-document', this.receiptId]);
      });

      throw error;
    }
  }

  addBreadcrumbIfNotExists() {
    const returnId = +this._activatedRoute.snapshot.params?.returnId;
    const receiptNumber = this._activatedRoute.snapshot.params?.receiptNumber;

    this._breadcrumb.addBreadcrumbIfNotExists({
      key: this._config.get('process.ids.remission'),
      name: 'Wannennummer scannen',
      path: `/filiale/remission/${returnId}/finish-shipping-document/${receiptNumber}`,
      params: this._activatedRoute.snapshot.queryParams,
      section: 'branch',
      tags: ['remission', 'finish-shipping-document'],
    });
  }
}
