import { Component, inject, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { DetailsRadioOption, IconButtonTypes, IqserDialogComponent } from '@iqser/common-ui';
import { Dictionary } from '@red/domain';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { DictionariesMapService } from '@services/entity-services/dictionaries-map.service';
import { getResizeRedactionOptions, ResizeOptions, ResizeRedactionOption } from '../../utils/dialog-options';
import { ResizeRedactionData, ResizeRedactionResult } from '../../utils/dialog-types';

@Component({
    templateUrl: './resize-redaction-dialog.component.html',
})
export class ResizeRedactionDialogComponent
    extends IqserDialogComponent<ResizeRedactionDialogComponent, ResizeRedactionData, ResizeRedactionResult>
    implements OnInit
{
    readonly #applyToAllDossiers = this.data.applyToAllDossiers ?? true;
    readonly #dossier = inject(ActiveDossiersService).find(this.data.dossierId);
    readonly iconButtonTypes = IconButtonTypes;
    readonly options: DetailsRadioOption<ResizeRedactionOption>[];
    dictionaries: Dictionary[] = [];
    readonly redaction = this.data.redaction;
    readonly form: FormGroup<{
        comment: FormControl<string>;
        dictionary: FormControl<string>;
        option: FormControl<DetailsRadioOption<ResizeRedactionOption>>;
    }>;

    constructor(
        private readonly _dictionariesMapService: DictionariesMapService,
        private readonly _formBuilder: FormBuilder,
    ) {
        super();
        this.options = getResizeRedactionOptions(this.redaction, this.#dossier, false, this.#applyToAllDossiers, this.data.isApprover);
        this.form = this.#getForm();
    }

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

    ngOnInit() {
        this.dictionaries = this._dictionariesMapService.get(this.#dossier.dossierTemplateId);
    }

    save() {
        const formValue = this.form.getRawValue();
        const updateDictionary = formValue.option.value === ResizeOptions.IN_DOSSIER;

        super.close({
            comment: formValue.comment,
            updateDictionary,
            addToAllDossiers: !!formValue.option?.extraOption?.checked,
        });
    }

    #getForm() {
        return this._formBuilder.group({
            comment: [null],
            dictionary: new FormControl({ value: this.redaction.entity.type, disabled: true }),
            option: this.options[0],
        });
    }
}
