import { Component, HostListener } from '@angular/core';
import {
    CircleButtonComponent,
    IconButtonComponent,
    IconButtonTypes,
    IqserDialogComponent,
    LoadingService,
    Toaster,
} from '@iqser/common-ui';
import { MatDialogClose } from '@angular/material/dialog';
import { MatFormField } from '@angular/material/form-field';
import { NgIf } from '@angular/common';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { MatCheckbox } from '@angular/material/checkbox';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';

interface DialogData {
    addToDictionaryAction: boolean;
    label: string;
    type: string;
    dossierTemplateId: string;
    dossierId: string;
    canEdit: boolean;
}

interface ReturnType {
    addToDictionaryAction: boolean;
}

@Component({
    selector: 'redaction-edit-dictionary-dialog',
    standalone: true,
    imports: [
        CircleButtonComponent,
        IconButtonComponent,
        MatDialogClose,
        MatFormField,
        ReactiveFormsModule,
        TranslateModule,
        MatCheckbox,
        NgIf,
    ],
    templateUrl: './edit-dictionary-dialog.component.html',
})
export class EditDictionaryDialogComponent extends IqserDialogComponent<EditDictionaryDialogComponent, DialogData, ReturnType> {
    readonly form = this._formBuilder.group({
        addToDictionaryAction: [{ value: this.data.addToDictionaryAction, disabled: !this.data.canEdit }],
    });
    readonly initialFormValue = this.form.getRawValue();

    constructor(
        private _formBuilder: FormBuilder,
        private _dictionaryService: DictionaryService,
        private _loadingService: LoadingService,
        private _toaster: Toaster,
    ) {
        super();
    }

    @HostListener('window:keydown.Escape')
    closeOnEscape(): void {
        this.close();
    }

    async save() {
        this._loadingService.start();
        try {
            await this._dictionaryService.updateFlag(
                this.data.dossierTemplateId,
                this.data.type,
                this.data.dossierId,
                this.form.controls.addToDictionaryAction.value,
            );
            this.close(this.form.value as ReturnType);
        } catch (error) {
            console.error(error);
            this._toaster.error(_('edit-dossier-dialog.dictionary.edit-dialog.error.generic'));
            this.close();
        }

        this._loadingService.stop();
    }
}
