import { effect, Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { TenantsService } from '@iqser/common-ui/lib/tenants';
import jwt_decode from 'jwt-decode';
import { KeycloakService } from 'keycloak-angular';
import { JwtToken } from '@guards/if-logged-in.guard';

const LAST_DOSSIERS_SCREEN = 'routerHistory_lastDossiersScreen';

@Injectable({
    providedIn: 'root',
})
export class RouterHistoryService {
    constructor(
        private readonly _router: Router,
        private readonly _tenantsService: TenantsService,
        private readonly _keycloakService: KeycloakService,
    ) {
        // eslint-disable-next-line rxjs/no-ignored-subscription
        this._router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((event: NavigationEnd) => {
            if (event.url.includes('/dossiers') || event.url.includes('/archive')) {
                const lastDossiersScreen = event.url;
                localStorage.setItem(LAST_DOSSIERS_SCREEN, lastDossiersScreen);
            }
            if (event.urlAfterRedirects.includes('/dashboard')) {
                localStorage.removeItem(LAST_DOSSIERS_SCREEN);
            }
        });
        const ref = effect(async () => {
            const token = await this._keycloakService.getToken();
            if (this._tenantsService.activeTenantId.length === 0 || !token) {
                return;
            }

            const jwtToken = jwt_decode(token) as JwtToken;
            const authTime = (jwtToken.auth_time || jwtToken.iat).toString();
            const localStorageAuthTime = localStorage.getItem('authTime');

            if (authTime.toString() !== localStorageAuthTime) {
                localStorage.removeItem(LAST_DOSSIERS_SCREEN);
            }

            ref.destroy();
        });
    }

    navigateToLastDossiersScreen(): void {
        const lastDossiersScreen = localStorage.getItem(LAST_DOSSIERS_SCREEN);
        if (this._router.url === decodeURI(lastDossiersScreen) || lastDossiersScreen === null) {
            this._router.navigate(['/' + this._tenantsService.activeTenantId]);
        } else {
            const url = decodeURI(lastDossiersScreen).split('?')[0];
            // todo links
            this._router.navigate([url]);
        }
    }
}
