import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { IconButtonTypes, ListingComponent, listingProvidersFactory, LoadingService, TableColumnConfig } from '@iqser/common-ui';
import { SortingOrders } from '@iqser/common-ui/lib/sorting';
import { getParam } from '@iqser/common-ui/lib/utils';
import { DOSSIER_TEMPLATE_ID, Justification } from '@red/domain';
import { JustificationsService } from '@services/entity-services/justifications.service';
import { PermissionsService } from '@services/permissions.service';
import { UserPreferenceService } from '@users/user-preference.service';
import { firstValueFrom } from 'rxjs';
import { JustificationsDialogService } from '../justifications-dialog.service';

@Component({
    selector: 'redaction-justifications-screen',
    templateUrl: './justifications-screen.component.html',
    styleUrls: ['./justifications-screen.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: listingProvidersFactory<Justification>({
        entitiesService: JustificationsService,
        component: JustificationsScreenComponent,
    }),
})
export class JustificationsScreenComponent extends ListingComponent<Justification> implements OnInit {
    readonly #dossierTemplateId = getParam(DOSSIER_TEMPLATE_ID);
    readonly iconButtonTypes = IconButtonTypes;
    readonly tableHeaderLabel = _('justifications-listing.table-header');
    readonly tableColumnConfigs: TableColumnConfig<Justification>[] = [
        { label: _('justifications-listing.table-col-names.name'), width: '2fr', sortByKey: 'name' },
        { label: _('justifications-listing.table-col-names.reason'), sortByKey: 'reason' },
        { label: _('justifications-listing.table-col-names.description'), width: '2fr' },
    ];
    readonly canAddEditJustifications = this.permissionsService.canAddEditJustifications();

    constructor(
        private readonly _justificationService: JustificationsService,
        private readonly _loadingService: LoadingService,
        private readonly _dialogService: JustificationsDialogService,
        readonly userPreferenceService: UserPreferenceService,
        readonly permissionsService: PermissionsService,
    ) {
        super();
    }

    async ngOnInit(): Promise<void> {
        this._loadingService.start();
        await firstValueFrom(this._justificationService.loadAll(this.#dossierTemplateId));
        this.sortingService.setSortingOption({
            column: 'name',
            order: SortingOrders.asc,
        });
        this._loadingService.stop();
    }

    openAddJustificationDialog(): void {
        this._dialogService.openDialog('addEditJustification', { justification: null, dossierTemplateId: this.#dossierTemplateId });
    }

    openConfirmDeleteDialog() {
        this._dialogService.confirmDelete(this.listingService.selected, this.#dossierTemplateId);
    }
}
