import { NavigationBreadcrumbsItem } from '@af/digi-ng/_navigation/navigation-breadcrumbs';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { UnsubscribeDirective } from '@msfa-directives/unsubscribe.directive';
import { Employee } from '@msfa-models/employee.model';
import { Organization } from '@msfa-models/organization.model';
import { Role } from '@msfa-models/role.model';
import { AuthenticationService } from '@msfa-services/api/authentication.service';
import { UserService } from '@msfa-services/api/user.service';
import { mapPathsToBreadcrumbs } from '@msfa-utils/map-paths-to-breadcrumbs.util';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'msfa-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LayoutComponent extends UnsubscribeDirective {
  @Input() showBreadCrumbs = true;
  private readonly _startBreadcrumb: NavigationBreadcrumbsItem = {
    text: 'Start',
    routerLink: '/',
  };
  private _breadcrumbsItems$ = new BehaviorSubject<NavigationBreadcrumbsItem[]>([this._startBreadcrumb]);
  isLoggedIn$: Observable<boolean> = this.authenticationService.isLoggedIn$;
  selectedOrganization$: Observable<Organization> = this.userService.selectedOrganization$;
  user$: Observable<Employee> = this.userService.user$.pipe(filter(user => !!user));
  roles$: Observable<Role[]> = this.userService.userRoles$.pipe(filter(roles => !!roles));
  userLoading$: Observable<boolean> = this.userService.userLoading$;
  rolesLoading$: Observable<boolean> = this.userService.userRolesLoading$;

  get breadcrumbsItems(): NavigationBreadcrumbsItem[] {
    return this._breadcrumbsItems$.getValue();
  }

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private authenticationService: AuthenticationService,
    private userService: UserService,
    private titleService: Title
  ) {
    super();
    super.unsubscribeOnDestroy(
      this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe(() => {
        const pageTitle = this.activatedRoute?.snapshot?.data?.title as string;
        const urlTree = this.router.parseUrl(this.router.url);

        this.titleService.setTitle(`${pageTitle ? `${pageTitle} - ` : ''}Mina sidor för fristående aktörer`);

        if (urlTree.queryParams.code) {
          void this.router.navigate([], {
            relativeTo: this.activatedRoute,
            queryParams: { code: null },
            queryParamsHandling: 'merge',
            replaceUrl: true,
          });
        }

        urlTree.queryParams = {};

        const paths = urlTree
          .toString()
          .split('/')
          .filter(path => !!path);
        this._breadcrumbsItems$.next(mapPathsToBreadcrumbs(paths, this._startBreadcrumb));
      })
    );
  }
}
