import { AsyncPipe, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { RouterLink } from '@angular/router';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { InputWithActionComponent } from '@common-ui/inputs/input-with-action/input-with-action.component';
import { getCurrentUser } from '@common-ui/users';
import { getParam } from '@common-ui/utils';
import {
    CircleButtonComponent,
    IconButtonComponent,
    IconButtonTypes,
    IqserAllowDirective,
    IqserDialog,
    IqserListingModule,
    ListingComponent,
    listingProvidersFactory,
    LoadingService,
    TableColumnConfig,
} from '@iqser/common-ui';
import { TranslateModule } from '@ngx-translate/core';
import { ComponentMapping, DOSSIER_TEMPLATE_ID, User } from '@red/domain';
import { ComponentMappingsService } from '@services/entity-services/component-mappings.service';
import { defaultColorsTranslations } from '@translations/default-colors-translations';
import { Roles } from '@users/roles';
import { combineLatest, firstValueFrom } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { AdminDialogService } from '../../services/admin-dialog.service';
import { AdminSideNavComponent } from '../../shared/components/admin-side-nav/admin-side-nav.component';
import { DossierTemplateActionsComponent } from '../../shared/components/dossier-template-actions/dossier-template-actions.component';
import { DossierTemplateBreadcrumbsComponent } from '../../shared/components/dossier-template-breadcrumbs/dossier-template-breadcrumbs.component';
import { AddEditComponentMappingDialogComponent } from './add-edit-component-mapping-dialog/add-edit-component-mapping-dialog.component';
import { download } from '@utils/file-download-utils';
import { MatTooltip } from '@angular/material/tooltip';

@Component({
    templateUrl: './component-mappings-screen.component.html',
    styleUrls: ['./component-mappings-screen.component.scss'],
    providers: listingProvidersFactory(ComponentMappingsScreenComponent),
    standalone: true,
    imports: [
        DossierTemplateBreadcrumbsComponent,
        AsyncPipe,
        NgIf,
        DossierTemplateActionsComponent,
        CircleButtonComponent,
        TranslateModule,
        RouterLink,
        AdminSideNavComponent,
        IqserListingModule,
        InputWithActionComponent,
        IconButtonComponent,
        IqserAllowDirective,
        MatTooltip,
    ],
})
export default class ComponentMappingsScreenComponent extends ListingComponent<ComponentMapping> implements OnInit {
    readonly #dossierTemplateId = getParam(DOSSIER_TEMPLATE_ID);
    protected readonly context$;
    protected readonly currentUser = getCurrentUser<User>();
    protected readonly translations = defaultColorsTranslations;
    protected readonly roles = Roles;
    protected readonly iconButtonTypes = IconButtonTypes;
    tableColumnConfigs: readonly TableColumnConfig<ComponentMapping>[] = [
        { label: _('component-mappings-screen.table-col-names.name'), sortByKey: 'searchKey' },
        { label: _('component-mappings-screen.table-col-names.version') },
        { label: _('component-mappings-screen.table-col-names.number-of-lines') },
        { label: _('component-mappings-screen.table-col-names.column-labels') },
    ];
    readonly tableHeaderLabel = _('component-mappings-screen.table-header.title');

    constructor(
        private readonly _loadingService: LoadingService,
        private readonly _componentMappingService: ComponentMappingsService,
        private readonly _iqserDialog: IqserDialog,
        private readonly _dialogService: AdminDialogService,
    ) {
        super();
        this.context$ = this.loadData$();
    }

    loadData$() {
        return combineLatest([this._componentMappingService.getComponentMappings(this.#dossierTemplateId)]).pipe(
            map(([mappingList]) => mappingList.componentMappingList),
            tap(mappings => this.entitiesService.setEntities(mappings)),
        );
    }

    ngOnInit() {
        this._loadingService.stop();
    }

    async openAddEditComponentMappingDialog(mapping?: ComponentMapping) {
        const dialog = this._iqserDialog.openDefault(AddEditComponentMappingDialogComponent, {
            data: {
                dossierTemplateId: this.#dossierTemplateId,
                mapping,
            },
        });
        const result = await dialog.result();
        if (result) {
            this._loadingService.start();
            const { id, name, encoding, delimiter } = result;
            const newMapping = { id, name, encoding, delimiter };
            await firstValueFrom(
                this._componentMappingService.createUpdateComponentMapping(this.#dossierTemplateId, newMapping, result.file),
            );
            await firstValueFrom(this.loadData$());
            this._loadingService.stop();
        }
    }

    async downloadMapping(entity: ComponentMapping) {
        const componentMappingFile = await firstValueFrom(
            this._componentMappingService.getComponentMappingFile(this.#dossierTemplateId, entity.id),
        );
        download(componentMappingFile, entity.fileName);
    }

    openDeleteComponentMappingDialog(entity: ComponentMapping) {
        this._dialogService.openDialog('confirm', null, async confirmation => {
            if (confirmation) {
                this._loadingService.start();
                await firstValueFrom(this._componentMappingService.deleteComponentMapping(this.#dossierTemplateId, entity.id));
                await firstValueFrom(this.loadData$());
                this._loadingService.stop();
            }
        });
    }
}
