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 { UiDialogModalComponent, UiErrorModalComponent, UiModalService } from '@ui/modal';
import { UiSearchboxNextComponent } from '@ui/searchbox';
import { Subject } from 'rxjs';
import { 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,
})
export class FinishShippingDocumentComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject<void>();

  @ViewChild(UiSearchboxNextComponent)
  searchboxComponent: UiSearchboxNextComponent;

  loading$ = new Subject<boolean>();

  hint$ = new Subject<string>();

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

  ngOnInit() {
    this.addBreadcrumbIfNotExists();
  }

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

  search(query: string) {
    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: {
        actions: [
          { label: 'Erneut scannen', command: false },
          { label: 'Nummer korrekt', selected: true, command: true },
        ],
      },
    });

    modal.afterClosed$.pipe(takeUntil(this._onDestroy$)).subscribe(async (result) => {
      if (result?.data) {
        if (await this.completeReceipt(query)) {
          await this.completeReturn();
        }

        await this.navigateToFinishRemission();
      } else {
        this.searchboxComponent.clear();
      }
    });
  }

  async completeReceipt(packageCode: string) {
    const returnId = +this._activatedRoute.snapshot.params?.returnId;
    const receiptId = +this._activatedRoute.snapshot.params?.receiptId;

    if (receiptId) {
      try {
        await this._remissionService.completeReceipt(returnId, receiptId, packageCode);
        return true;
      } catch (err) {
        this._modal.open({
          content: UiErrorModalComponent,
          title: 'Fehler beim Abschließen des Warenbegleitscheins',
          data: err,
        });
      }
    } else {
      this._modal.open({
        content: UiErrorModalComponent,
        title: 'Fehler beim Abschließen des Warenbegleitscheins',
        data: new Error('Keine gültige ID'),
      });
    }
    return false;
  }

  async completeReturn() {
    const returnId = +this._activatedRoute.snapshot.params?.returnId;

    if (returnId) {
      try {
        await this._remissionService.completeReturn(returnId);
      } catch (err) {
        this._modal.open({
          content: UiErrorModalComponent,
          title: 'Fehler beim Abschließen der Remission',
          data: err,
        });
      }
    } else {
      this._modal.open({
        content: UiErrorModalComponent,
        title: 'Fehler beim Abschließen der Remission',
        data: new Error('Keine gültige ID'),
      });
    }
  }

  async navigateToFinishRemission() {
    await this._router.navigate(['../../', 'finish-remission'], {
      relativeTo: this._activatedRoute,
      queryParams: { ...this.cleanupQueryParams(this._activatedRoute.snapshot.queryParams) },
    });
  }

  cleanupQueryParams(params: Record<string, string> = {}) {
    const clean = { ...params };
    delete clean['scroll_position'];

    for (const key in clean) {
      if (Object.prototype.hasOwnProperty.call(clean, key)) {
        if (clean[key] == undefined) {
          delete clean[key];
        }
      }
    }

    return clean;
  }

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

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