import { ChangeDetectionStrategy, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { Dossier, DOSSIER_TEMPLATE_ID, DossierTemplate } from '@red/domain';
import { PermissionsService } from '@services/permissions.service';
import { ButtonConfig, ListingComponent, listingProvidersFactory, LoadingService, TableComponent } from '@iqser/common-ui';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { ConfigService } from '../config.service';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { UserPreferenceService } from '@users/user-preference.service';
import { SharedDialogService } from '@shared/services/dialog.service';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { OnAttach } from '@iqser/common-ui/lib/utils';

@Component({
    templateUrl: './dossiers-listing-screen.component.html',
    styleUrls: ['./dossiers-listing-screen.component.scss'],
    providers: listingProvidersFactory(DossiersListingScreenComponent),
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DossiersListingScreenComponent extends ListingComponent<Dossier> implements OnInit, OnAttach {
    @ViewChild('needsWorkFilterTemplate', {
        read: TemplateRef,
        static: true,
    })
    private readonly _needsWorkFilterTemplate: TemplateRef<unknown>;
    @ViewChild(TableComponent) private readonly _tableComponent: TableComponent<Dossier>;
    readonly tableColumnConfigs = this._configService.tableConfig;
    readonly tableHeaderLabel = _('dossier-listing.table-header.title');
    readonly buttonConfigs: ButtonConfig[];
    readonly dossierTemplate: DossierTemplate;
    readonly computeFilters$ = this._activeDossiersService.all$.pipe(tap(() => this._computeAllFilters()));

    constructor(
        router: Router,
        private readonly _configService: ConfigService,
        readonly permissionsService: PermissionsService,
        private readonly _dialogService: SharedDialogService,
        private readonly _activeDossiersService: ActiveDossiersService,
        private readonly _userPreferenceService: UserPreferenceService,
        private readonly _loadingService: LoadingService,
        dossierTemplatesService: DossierTemplatesService,
    ) {
        super();
        const dossierTemplateId = router.routerState.snapshot.root.firstChild.firstChild.paramMap.get(DOSSIER_TEMPLATE_ID);
        this.dossierTemplate = dossierTemplatesService.find(dossierTemplateId);
        this.buttonConfigs = this._configService.buttonsConfig(this.dossierTemplate);
        this.entitiesService.setEntities(this._activeDossiersService.all.filter(d => d.dossierTemplateId === this.dossierTemplate.id));
    }

    openAddDossierDialog(): void {
        this._dialogService.openDialog('addDossier', { dossierTemplateId: this.dossierTemplate.id });
    }

    async ngOnInit(): Promise<void> {
        await this._userPreferenceService.saveLastDossierTemplate(this.dossierTemplate.id);
        this.addSubscription = this._activeDossiersService.all$
            .pipe(tap(dossiers => this.entitiesService.setEntities(dossiers.filter(d => d.dossierTemplateId === this.dossierTemplate.id))))
            .subscribe();
        this._loadingService.stop();
    }

    ngOnAttach(): void {
        this._tableComponent?.scrollToLastIndex();
        this._loadingService.stop();
    }

    private _computeAllFilters() {
        const filterGroups = this._configService.filterGroups(
            this.entitiesService.all,
            this._needsWorkFilterTemplate,
            this.dossierTemplate.id,
        );
        this.filterService.addFilterGroups(filterGroups);
    }
}
