import { Component, inject, OnDestroy, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { IqserPermissionsService, ListingComponent, listingProvidersFactory, LoadingService, TableColumnConfig } from '@iqser/common-ui';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { Audit, IAudit, IAuditResponse, IAuditSearchRequest, User } from '@red/domain';
import { RouterHistoryService } from '@services/router-history.service';
import { auditCategoriesTranslations } from '@translations/audit-categories-translations';
import { Roles } from '@users/roles';
import { applyIntervalConstraints } from '@utils/date-inputs-utils';
import { Dayjs } from 'dayjs';
import { firstValueFrom } from 'rxjs';
import { AdminDialogService } from '../../services/admin-dialog.service';
import { AuditService } from '../../services/audit.service';

const PAGE_SIZE = 50;

@Component({
    templateUrl: './audit-screen.component.html',
    styleUrls: ['./audit-screen.component.scss'],
    providers: listingProvidersFactory(AuditScreenComponent),
})
export class AuditScreenComponent extends ListingComponent<Audit> implements OnInit, OnDestroy {
    private _previousFrom: Dayjs;
    private _previousTo: Dayjs;
    readonly ALL_CATEGORIES = 'allCategories';
    readonly ALL_USERS = _('audit-screen.all-users');
    readonly translations = auditCategoriesTranslations;
    readonly form: UntypedFormGroup = this._getForm();
    readonly routerHistoryService = inject(RouterHistoryService);
    readonly permissionsService = inject(IqserPermissionsService);
    readonly roles = Roles;
    readonly currentUser = getCurrentUser<User>();
    categories: string[] = [];
    userIds: Set<string>;
    logs: IAuditResponse;
    readonly tableColumnConfigs: TableColumnConfig<Audit>[] = [
        { label: _('audit-screen.table-col-names.message') },
        { label: _('audit-screen.table-col-names.date') },
        { label: _('audit-screen.table-col-names.user'), class: 'user-column' },
        { label: _('audit-screen.table-col-names.category') },
    ];
    readonly tableHeaderLabel = _('audit-screen.table-header.title');

    constructor(
        private readonly _formBuilder: UntypedFormBuilder,
        private readonly _loadingService: LoadingService,
        private readonly _auditService: AuditService,
        private readonly _dialogService: AdminDialogService,
    ) {
        super();
    }

    get totalPages(): number {
        if (!this.logs) {
            return 0;
        }
        return Math.ceil(this.logs.totalHits / PAGE_SIZE);
    }

    async pageChanged(page: number) {
        await this._fetchData(page);
    }

    async ngOnInit() {
        this.sortingService.setSortingOption({ column: 'recordDate', order: 'desc' });
        await this._fetchData();
    }

    async filterChange() {
        if (!this._updateDateFilters(this.form.value)) {
            await this._fetchData();
        }
    }

    openAuditDetails(log: Audit) {
        this._dialogService.openDialog('auditInfo', { auditEntry: log });
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            category: [this.ALL_CATEGORIES],
            userId: [this.ALL_USERS],
            from: [],
            to: [],
        });
    }

    private _updateDateFilters(value): boolean {
        if (applyIntervalConstraints(value, this._previousFrom, this._previousTo, this.form, 'from', 'to')) {
            return true;
        }

        this._previousFrom = this.form.get('from').value;
        this._previousTo = this.form.get('to').value;
        return false;
    }

    private async _fetchData(page?: number) {
        this._loadingService.start();
        const promises = [];
        const category = this.form.get('category').value;
        const userId = this.form.get('userId').value;
        const from = this.form.get('from').value;
        let to = this.form.get('to').value;
        if (to) {
            to = to.clone().add(1, 'd');
        }
        const logsRequestBody: IAuditSearchRequest = {
            pageSize: PAGE_SIZE,
            page: page,
            category: category === this.ALL_CATEGORIES ? undefined : category,
            userId: userId === this.ALL_USERS ? undefined : userId,
            from,
            to,
        };

        promises.push(firstValueFrom(this._auditService.getCategories()));
        promises.push(firstValueFrom(this._auditService.searchAuditLog(logsRequestBody)));

        const data = await Promise.all(promises);
        this.categories = data[0].map(c => c.category);
        this.categories.splice(0, 0, this.ALL_CATEGORIES);
        this.logs = data[1];
        const entities = this.logs.data.map((log: IAudit) => new Audit(log));
        this.entitiesService.setEntities(entities);
        this.userIds = new Set<string>([this.ALL_USERS]);
        for (const id of this.logs.data.map(log => log.userId).filter(uid => !!uid)) {
            this.userIds.add(id);
        }
        this._loadingService.stop();
    }
}
