import { Component, inject, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { IconButtonTypes, IqserDialogComponent } from '@iqser/common-ui';
import { Dictionary, IAddRedactionRequest } from '@red/domain';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { AddAnnotationData, AddAnnotationResult } from '../../../utils/dialog-types';

@Component({
    templateUrl: './add-annotation-dialog.component.html',
})
export class AddAnnotationDialogComponent
    extends IqserDialogComponent<AddAnnotationDialogComponent, AddAnnotationData, AddAnnotationResult>
    implements OnInit
{
    readonly #dossier = inject(ActiveDossiersService).find(this.data.dossierId);
    readonly iconButtonTypes = IconButtonTypes;
    dictionaries: Dictionary[] = [];
    readonly form = this.#getForm();

    constructor(
        private readonly _dictionaryService: DictionaryService,
        private readonly _formBuilder: FormBuilder,
    ) {
        super();
    }

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

    get disabled() {
        return !this.form.controls.dictionary.value;
    }

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

    save(): void {
        this.#enhanceManualRedaction(this.data.manualRedactionEntryWrapper.manualRedactionEntry);
        const redaction = this.data.manualRedactionEntryWrapper.manualRedactionEntry;
        this.close({
            redaction,
            dictionary: this.dictionaries.find(d => d.type === this.form.controls.dictionary.value),
        });
    }

    #getForm() {
        return this._formBuilder.group({
            selectedText: this.data?.manualRedactionEntryWrapper?.manualRedactionEntry?.value,
            comment: [null],
            dictionary: [null],
        });
    }

    #enhanceManualRedaction(addRedactionRequest: IAddRedactionRequest) {
        addRedactionRequest.type = this.form.controls.dictionary.value;

        const selectedType = this.dictionaries.find(d => d.type === addRedactionRequest.type);
        addRedactionRequest.addToDictionary = !!selectedType?.hasDictionary;
        addRedactionRequest.reason ??= 'Dictionary Request';

        const commentValue = this.form.controls.comment.value;
        addRedactionRequest.comment = commentValue ? { text: commentValue } : null;
        addRedactionRequest.section = null;
        addRedactionRequest.value = this.form.controls.selectedText.value;
        addRedactionRequest.addToAllDossiers = addRedactionRequest.addToDictionary || !!this.data.applyToAllDossiers;
    }
}
