import { Component, ChangeDetectionStrategy, OnInit, OnDestroy, Optional, Inject } 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 { UiModalService } from '@ui/modal';
import { NEVER, Subject } from 'rxjs';
import { catchError, switchMap, takeUntil, tap } from 'rxjs/operators';
import { AddProductModalComponent, AddProductModalData } from '../modals/add-product-modal';
import { RemissionListComponentStore } from '../remission-list/remission-list.component-store';

@Component({
  selector: 'page-remission-add-product',
  templateUrl: 'add-product.component.html',
  styleUrls: ['add-product.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AddProductComponent implements OnInit, OnDestroy {
  private _onDestroy = new Subject<void>();

  loading$ = new Subject<boolean>();

  search$ = new Subject<string>();

  hint$ = new Subject<string>();

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

  constructor(
    private readonly _remissionListStore: RemissionListComponentStore,
    private _remiService: DomainRemissionService,
    private _modal: UiModalService,
    private _breadcrumb: BreadcrumbService,
    private _config: Config,
    private _router: Router,
    private _activatedRoute: ActivatedRoute
  ) {}

  ngOnInit() {
    this.addBreadcrumbIfNotExists();
    this.initSearch();
  }

  initSearch() {
    this.search$
      .pipe(
        tap((_) => {
          this.loading$.next(true);
          this.hint$.next('');
        }),
        switchMap((query) =>
          this._remiService.searchItemToRemit(query).pipe(
            catchError((e) => {
              let message = 'Fehler beim Laden der Produkte';
              if (e.error?.invalidProperties) {
                message = Object.values(e.error.invalidProperties).join(', ');
              }
              this.hint$.next(message || e.error?.message);
              this.loading$.next(false);
              return NEVER;
            }),
            tap(() => this.loading$.next(false))
          )
        )
      )
      .subscribe((result) => {
        if (!result) {
          this.hint$.next('Keine Produkte gefunden');
        } else {
          const modal = this._modal.open({
            content: AddProductModalComponent,
            title: 'Artikel zur Remi-Liste hinzufügen',
            data: {
              item: result,
            } as AddProductModalData,
          });
          modal.afterClosed$.pipe(takeUntil(this._onDestroy)).subscribe((result) => {
            if (result.data) {
              this._remissionListStore._triggerReload$.next(true);
              this._router.navigate(['..', 'list'], { relativeTo: this._activatedRoute, queryParams: this.queryParams });
            }
          });
        }
      });
  }

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

    this.loading$.complete();
    this.search$.complete();
    this.hint$.complete();
  }

  search(query: string) {
    if (query.length > 0) {
      this.search$.next(query);
    } else {
      this.hint$.next('Bitte geben Sie einen ISBN/EAN ein');
    }
  }

  addBreadcrumbIfNotExists() {
    this._breadcrumb.addBreadcrumbIfNotExists({
      key: this._config.get('process.ids.remission'),
      name: 'Artikel hinzufügen',
      path: '/filiale/remission/add-product',
      section: 'branch',
      params: this.queryParams,
      tags: ['remission', 'add-product'],
    });
  }
}
