import { ChangeDetectionStrategy, Component, Inject } from '@angular/core';
import { UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Justification } from '@red/domain';
import { JustificationsService } from '@services/entity-services/justifications.service';
import { BaseDialogComponent } from '@iqser/common-ui';
import { firstValueFrom } from 'rxjs';

interface DialogData {
    justification?: Justification;
    dossierTemplateId: string;
}

@Component({
    templateUrl: './add-edit-justification-dialog.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AddEditJustificationDialogComponent extends BaseDialogComponent {
    constructor(
        private readonly _justificationService: JustificationsService,
        protected readonly _dialogRef: MatDialogRef<AddEditJustificationDialogComponent>,
        @Inject(MAT_DIALOG_DATA) readonly data: DialogData,
    ) {
        super(_dialogRef, !!data.justification);

        this.form = this._getForm();
        this.initialFormValue = this.form.getRawValue();
    }

    async save() {
        const dossierTemplateId = this.data.dossierTemplateId;
        this._loadingService.start();
        try {
            await firstValueFrom(this._justificationService.createOrUpdate(this.form.getRawValue() as Justification, dossierTemplateId));
            await firstValueFrom(this._justificationService.loadAll(dossierTemplateId));
            this._dialogRef.close(true);
        } catch (error) {
            this._toaster.rawError(error.error.message);
        }
        this._loadingService.stop();
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            name: [{ value: this.data.justification?.name, disabled: !!this.data.justification }, Validators.required],
            reason: [this.data.justification?.reason, Validators.required],
            description: [this.data.justification?.description, Validators.required],
        });
    }
}
