import { Component, ChangeDetectionStrategy, Input, OnInit } from '@angular/core';
import { Breadcrumb, BreadcrumbService } from '@core/breadcrumb';
import { BehaviorSubject, combineLatest, merge, Observable, of } from 'rxjs';
import { filter, map, switchMap } from 'rxjs/operators';
import { NavigationEnd, Router } from '@angular/router';

@Component({
  selector: 'shell-breadcrumb',
  templateUrl: 'shell-breadcrumb.component.html',
  styleUrls: ['shell-breadcrumb.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShellBreadcrumbComponent implements OnInit {
  @Input()
  set key(value: string) {
    this.keyChanges$.next(value);
  }

  @Input()
  set includesTags(tags: string[]) {
    this.includesTagsChanges$.next(tags || []);
  }

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

  includesTagsChanges$ = new BehaviorSubject<string[]>([]);

  readonly breadcrumbs$: Observable<Breadcrumb[]> = combineLatest([this.keyChanges$, this.includesTagsChanges$]).pipe(
    switchMap(([key, tags]) => this.breadcrumbService.getBreadcrumbsByKeyAndTags$(key, tags))
  );

  activatedBreadcrumb$: Observable<Breadcrumb>;

  previousBreadcrumb$: Observable<Breadcrumb>;

  constructor(public breadcrumbService: BreadcrumbService, private router: Router) {}

  ngOnInit(): void {
    const navigated$ = merge(of(undefined), this.router.events.pipe(filter((event) => event instanceof NavigationEnd)));

    this.activatedBreadcrumb$ = combineLatest([this.breadcrumbs$, navigated$]).pipe(
      map(([crumbs]) => {
        const activated = crumbs.find((crumb) => this.router.url.split('?')[0].endsWith(crumb.path));

        if (activated) {
          // this.breadcrumbService.removeBreadcrumbsAfter(activated.id);
          return activated;
        }
      }),
      filter((a) => !!a)
    );

    this.previousBreadcrumb$ = combineLatest([this.breadcrumbs$, this.activatedBreadcrumb$]).pipe(
      map(([crumbs, activated]) => {
        const previousCrumIndex = crumbs.findIndex((crumb) => crumb?.id === activated?.id) - 1;
        if (previousCrumIndex >= 0) {
          return crumbs[previousCrumIndex];
        }
      })
    );
  }
}
