import { Component, Inject, OnInit } from '@angular/core';
import { UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { PermissionsService } from '@services/permissions.service';
import { Dictionary, Dossier } from '@red/domain';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { BaseDialogComponent } from '@iqser/common-ui';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { acceptRecommendationTranslations } from '@translations/accept-recommendation-translations';

export interface AcceptRecommendationData {
    readonly annotations: AnnotationWrapper[];
    readonly dossierId: string;
}

export interface AcceptRecommendationReturnType {
    readonly annotations: AnnotationWrapper[];
    readonly comment: string;
}

@Component({
    templateUrl: './accept-recommendation-dialog.component.html',
})
export class AcceptRecommendationDialogComponent extends BaseDialogComponent implements OnInit {
    readonly dialogHeader: string;

    possibleDictionaries: Dictionary[] = [];

    private readonly _dossier: Dossier;

    constructor(
        permissionsService: PermissionsService,
        activeDossiersService: ActiveDossiersService,
        private readonly _dictionaryService: DictionaryService,
        protected readonly _dialogRef: MatDialogRef<AcceptRecommendationDialogComponent, AcceptRecommendationReturnType>,
        @Inject(MAT_DIALOG_DATA) readonly data: AcceptRecommendationData,
    ) {
        super(_dialogRef);
        this._dossier = activeDossiersService.find(this.data.dossierId);
        const isDocumentAdmin = permissionsService.isApprover(this._dossier);
        this.dialogHeader = isDocumentAdmin
            ? acceptRecommendationTranslations.addToDictionary
            : acceptRecommendationTranslations.requestAddToDictionary;
        this.form = this._getForm();
        this.initialFormValue = this.form.getRawValue();
    }

    get displayedDictionaryLabel() {
        const dictType = this.form.get('dictionary').value as string;
        if (dictType && this.possibleDictionaries.length) {
            return this.possibleDictionaries.find(d => d.type === dictType)?.label;
        }
        return null;
    }

    async ngOnInit() {
        this.possibleDictionaries = await this._dictionaryService.getDictionariesOptions(this._dossier.dossierTemplateId, this._dossier.id);
        this.form.patchValue({
            dictionary: this.possibleDictionaries.find(dict => dict.type === this.data.annotations[0].recommendationType)?.type,
        });
    }

    save() {
        const recommendationType = this.form.get('dictionary').value;
        this.data.annotations.forEach(a => (a.recommendationType = recommendationType));
        this._dialogRef.close({
            annotations: this.data.annotations,
            comment: this.form.get('comment').value as string,
        });
    }

    format(value: string) {
        return value.replace(
            // eslint-disable-next-line no-control-regex,max-len
            /([^\s\d-]{2,})[-\u00AD]\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]/gi,
            '$1',
        );
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            dictionary: [Validators.required],
            comment: [null],
        });
    }
}
