import {
  ChangeDetectorRef,
  OnDestroy,
  Pipe,
  PipeTransform,
} from '@angular/core';
import { ApplicationService } from '@core/application';
import { ProductCatalogNavigationService } from '@shared/services/navigation';
import { isEqual } from 'lodash';
import { Subscription, combineLatest, BehaviorSubject } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
import { REIHE_PREFIX_PATTERN } from './reihe.constants';

@Pipe({
  name: 'reiheRoute',
  standalone: true,
  pure: false,
})
export class ReiheRoutePipe implements PipeTransform, OnDestroy {
  private subscription: Subscription;

  value$ = new BehaviorSubject<string>('');

  result: { path: string[]; queryParams?: Record<string, string> };

  constructor(
    private navigation: ProductCatalogNavigationService,
    private application: ApplicationService,
    private cdr: ChangeDetectorRef,
  ) {
    this.subscription = combineLatest([
      this.application.activatedProcessId$,
      this.value$,
    ])
      .pipe(distinctUntilChanged(isEqual))
      .subscribe(([processId, value]) => {
        const REIHE_REGEX = new RegExp(`[";]|${REIHE_PREFIX_PATTERN}:`, 'g'); // Entferne jedes Semikolon, Anführungszeichen und den String Reihe:/Reihe/Set:/Set/Reihe:
        const reihe = value?.replace(REIHE_REGEX, '')?.trim();

        if (!reihe) {
          this.result = null;
          return;
        }

        // Entferne Zahlen am Ende, die mit Leerzeichen, Komma, Slash oder Semikolon getrennt sind
        // Beispiele: "Harry Potter 1" -> "Harry Potter", "Harry Potter,1" -> "Harry Potter", "Harry Potter/2" -> "Harry Potter"
        const main_qs = reihe
          .split('/')[0]
          .replace(/[\s,;]+\d+$/g, '')
          .trim();

        const path =
          this.navigation.getArticleSearchResultsPath(processId).path;

        this.result = {
          path,
          queryParams: {
            main_qs,
            main_serial: 'serial',
          },
        };

        this.cdr.detectChanges();
      });
  }

  ngOnDestroy(): void {
    this.subscription?.unsubscribe();
    this.value$?.unsubscribe();
  }

  transform(value: string, ...args: any[]) {
    this.value$.next(value);

    return this.result;

    // const REIHE_REGEX = /^Reihe:\s*"(.+)\"$/g;
    // const reihe = REIHE_REGEX.exec(value)?.[1];

    // this.navigation.getArticleSearchResultsPath(this.)

    // return reihe ? `/search?query=${reihe}` : null;
  }
}
