import { Component, OnInit } from '@angular/core';
import { IconButtonTypes, IqserDialogComponent, IqserPermissionsService } from '@iqser/common-ui';
import { Dictionary, Dossier, SuperTypes } from '@red/domain';
import { FormBuilder, UntypedFormGroup } from '@angular/forms';
import { Roles } from '@users/roles';
import { JustificationsService } from '@services/entity-services/justifications.service';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { EditRedactionData, EditRedactResult } from '../../../utils/dialog-types';

@Component({
    templateUrl: 'edit-annotation-dialog.component.html',
    styleUrls: ['edit-annotation-dialog.component.scss'],
})
export class EditAnnotationDialogComponent
    extends IqserDialogComponent<EditAnnotationDialogComponent, EditRedactionData, EditRedactResult>
    implements OnInit
{
    readonly roles = Roles;
    readonly iconButtonTypes = IconButtonTypes;
    readonly redactedTexts: string[];
    dictionaries: Dictionary[] = [];
    form: UntypedFormGroup;
    readonly #dossier: Dossier;

    constructor(
        private readonly _justificationsService: JustificationsService,
        private readonly _activeDossiersService: ActiveDossiersService,
        private readonly _dictionaryService: DictionaryService,
        private readonly _iqserPermissionsService: IqserPermissionsService,
        private readonly _formBuilder: FormBuilder,
    ) {
        super();
        this.#dossier = _activeDossiersService.find(this.data.dossierId);
        const annotations = this.data.annotations;
        this.redactedTexts = annotations.map(annotation => annotation.value);
        this.form = this.#getForm();
        this.initialFormValue = JSON.parse(JSON.stringify(this.form.getRawValue()));
    }

    get displayedDictionaryLabel() {
        const selectedDictionaryType = this.form.get('type').value;
        if (selectedDictionaryType) {
            return this.dictionaries.find(d => d.type === selectedDictionaryType)?.label ?? null;
        }
        return null;
    }

    get showList() {
        return this.data.annotations.every(annotation => annotation.isSkipped || annotation.isRedacted);
    }

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

    reasonChanged() {
        this.form.patchValue({ reason: this.dictionaries.find(d => d.type === SuperTypes.ManualRedaction) });
    }

    save(): void {
        const value = this.form.value;
        this.dialogRef.close({
            comment: value.comment,
            type: value.type,
        });
    }

    #setTypes() {
        this.dictionaries = this._dictionaryService.getRedactionTypes(this.#dossier.dossierTemplateId);
    }

    #getForm(): UntypedFormGroup {
        const sameType = new Set(this.data.annotations.map(annotation => annotation.type)).size === 1;
        return this._formBuilder.group({
            comment: [null],
            type: [sameType ? this.data.annotations[0].type : null],
        });
    }

    #allRectangles() {
        return this.data.annotations.reduce((acc, a) => acc && a.rectangle, true);
    }
}
