import { Component, inject } from '@angular/core';
import { UserService } from '@users/user.service';
import { UserPreferenceService } from '@users/user-preference.service';
import { ActivatedRoute, NavigationStart, ParamMap, Router } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';
import { SpotlightSearchAction } from '@components/spotlight-search/spotlight-search-action';
import { filter, map, startWith } from 'rxjs/operators';
import { getConfig, IqserPermissionsService } from '@iqser/common-ui';
import { BreadcrumbsService } from '@services/breadcrumbs.service';
import { FeaturesService } from '@services/features.service';
import { ARCHIVE_ROUTE, DOSSIERS_ARCHIVE, DOSSIERS_ROUTE } from '@red/domain';
import { Roles } from '@users/roles';
import { REDDocumentViewer } from '../../modules/pdf-viewer/services/document-viewer.service';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { List, shareDistinctLast } from '@iqser/common-ui/lib/utils';
import { TenantsService } from '@iqser/common-ui/lib/tenants';

const isNavigationStart = (event: unknown): event is NavigationStart => event instanceof NavigationStart;
const isSearchScreen: (url: string) => boolean = url => url.includes('/search');

@Component({
    templateUrl: './base-screen.component.html',
    styleUrls: ['./base-screen.component.scss'],
})
export class BaseScreenComponent {
    readonly #navigationStart$ = this._router.events.pipe(
        filter(isNavigationStart),
        map(event => event.url),
        startWith(this._router.url),
        shareDistinctLast(),
    );
    readonly roles = Roles;
    readonly documentViewer = inject(REDDocumentViewer);
    readonly currentUser = this.userService.currentUser;
    readonly searchActions: List<SpotlightSearchAction> = [
        {
            text: this._translateService.instant('search.this-dossier'),
            icon: 'red:enter',
            hide: (): boolean => this.#hideSearchThisDossier,
            action: (query): void => this.#searchThisDossier(query),
        },
        {
            text: this._translateService.instant('search.active-dossiers'),
            icon: 'red:enter',
            hide: () => !this._featuresService.isEnabled(DOSSIERS_ARCHIVE),
            action: (query): void => this.#search(query, [], true),
        },
        {
            text: this._translateService.instant('search.all-dossiers'),
            icon: 'red:enter',
            action: (query): void => this.#search(query, []),
        },
    ];
    readonly isSearchScreen$ = this.#navigationStart$.pipe(map(isSearchScreen));
    readonly config = getConfig();

    constructor(
        private readonly _router: Router,
        activatedRoute: ActivatedRoute,
        private readonly _translateService: TranslateService,
        private readonly _featuresService: FeaturesService,
        protected readonly _tenantsService: TenantsService,
        readonly permissionsService: IqserPermissionsService,
        readonly userService: UserService,
        readonly userPreferenceService: UserPreferenceService,
        readonly titleService: Title,
        readonly breadcrumbsService: BreadcrumbsService,
    ) {
        // eslint-disable-next-line rxjs/no-ignored-subscription
        activatedRoute.queryParamMap.pipe(takeUntilDestroyed()).subscribe(queryParams => this.#navigate(queryParams));
    }

    get #hideSearchThisDossier() {
        const routerLink = this.breadcrumbsService.breadcrumbs[1]?.options?.routerLink;
        if (!routerLink) {
            return true;
        }

        const isDossierOverview = (routerLink.includes(DOSSIERS_ROUTE) || routerLink.includes(ARCHIVE_ROUTE)) && routerLink.length === 3;
        return !isDossierOverview;
    }

    #navigate(queryParams: ParamMap) {
        if (queryParams.has('username')) {
            return this._router.navigate([], {
                queryParams: {
                    username: null,
                },
                queryParamsHandling: 'merge',
            });
        }
    }

    #search(query: string, dossierIds: string[], onlyActive = false) {
        const queryParams = { query, dossierIds: dossierIds.join(','), onlyActive };
        this._router.navigate([`/${this._tenantsService.activeTenantId}/main/search`], { queryParams }).then();
    }

    #searchThisDossier(query: string) {
        const routerLink = this.breadcrumbsService.breadcrumbs[1]?.options?.routerLink;
        if (!routerLink) {
            return this.#search(query, []);
        }
        const dossierId = routerLink[2];
        return this.#search(query, [dossierId]);
    }
}
