import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
    defaultDialogConfig,
    IconButtonTypes,
    ListingComponent,
    listingProvidersFactory,
    LoadingService,
    TableColumnConfig,
} from '@iqser/common-ui';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { getParam } from '@iqser/common-ui/lib/utils';
import { DOSSIER_TEMPLATE_ID, DossierAttributeConfig, IDossierAttributeConfig, User } from '@red/domain';
import { DossierAttributesService } from '@services/entity-services/dossier-attributes.service';
import { PermissionsService } from '@services/permissions.service';
import { firstValueFrom } from 'rxjs';
import { AdminDialogService } from '../../services/admin-dialog.service';
import {
    AddEditDossierAttributeDialogComponent,
    AddEditDossierAttributeDialogData,
} from './add-edit-dossier-attribute-dialog/add-edit-dossier-attribute-dialog.component';

@Component({
    templateUrl: './dossier-attributes-listing-screen.component.html',
    styleUrls: ['./dossier-attributes-listing-screen.component.scss'],
    providers: listingProvidersFactory<DossierAttributeConfig>({
        entitiesService: DossierAttributesService,
        component: DossierAttributesListingScreenComponent,
    }),
})
export class DossierAttributesListingScreenComponent extends ListingComponent<DossierAttributeConfig> implements OnInit {
    readonly #dossierTemplateId = getParam(DOSSIER_TEMPLATE_ID);
    readonly iconButtonTypes = IconButtonTypes;
    readonly currentUser = getCurrentUser<User>();
    readonly tableHeaderLabel = _('dossier-attributes-listing.table-header.title');
    readonly tableColumnConfigs: TableColumnConfig<DossierAttributeConfig>[] = [
        { label: _('dossier-attributes-listing.table-col-names.label'), sortByKey: 'label', width: '2fr' },
        { label: _('dossier-attributes-listing.table-col-names.placeholder'), width: '2fr' },
        { label: _('dossier-attributes-listing.table-col-names.type'), sortByKey: 'type' },
    ];
    @ViewChild('impactedTemplates') impactedTemplatesRef: TemplateRef<unknown>;
    readonly canEditDossierAttributes = this.permissionsService.canEditGlobalDossierAttributes();

    constructor(
        readonly permissionsService: PermissionsService,
        private readonly _loadingService: LoadingService,
        private readonly _dialogService: AdminDialogService,
        private readonly _dialog: MatDialog,
        private readonly _dossierAttributesService: DossierAttributesService,
    ) {
        super();
    }

    async ngOnInit(): Promise<void> {
        await this.#loadData();
    }

    async openConfirmDeleteAttributeDialog(attributes: DossierAttributeConfig[] = this.listingService.selected) {
        await this._dialogService.deleteAttributes(attributes, this.#dossierTemplateId, this.impactedTemplatesRef, 'dossier', async () => {
            this._loadingService.start();
            const ids = attributes.map(a => a.id);
            await firstValueFrom(this._dossierAttributesService.delete(ids, this.#dossierTemplateId));
            await this.#loadData();
        });
    }

    async openAddEditAttributeDialog(dossierAttribute?: IDossierAttributeConfig) {
        const dossierTemplateId = this.#dossierTemplateId;

        const ref = this._dialog.open<AddEditDossierAttributeDialogComponent, AddEditDossierAttributeDialogData, boolean>(
            AddEditDossierAttributeDialogComponent,
            {
                ...defaultDialogConfig,
                autoFocus: true,
                data: { dossierAttribute, dossierTemplateId },
            },
        );

        const result = await firstValueFrom(ref.afterClosed());

        if (result) {
            await this.#loadData();
        }
    }

    async #loadData() {
        this._loadingService.start();
        await firstValueFrom(this._dossierAttributesService.loadAll(this.#dossierTemplateId));
        this._loadingService.stop();
    }
}
