import { Component, Inject, OnDestroy } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { DossierAttributeConfigTypes, FileAttributeConfigTypes, IDossierAttributeConfig } from '@red/domain';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { BaseDialogComponent, CircleButtonComponent, IconButtonComponent } from '@iqser/common-ui';
import { HttpErrorResponse } from '@angular/common/http';
import { DossierAttributesService } from '@services/entity-services/dossier-attributes.service';
import { dossierAttributeTypesTranslations } from '@translations/dossier-attribute-types-translations';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { TranslateModule } from '@ngx-translate/core';
import { NgForOf, NgIf } from '@angular/common';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';

export interface AddEditDossierAttributeDialogData {
    readonly dossierAttribute: IDossierAttributeConfig;
    readonly dossierTemplateId: string;
}

@Component({
    templateUrl: './add-edit-dossier-attribute-dialog.component.html',
    styleUrls: ['./add-edit-dossier-attribute-dialog.component.scss'],
    standalone: true,
    imports: [
        TranslateModule,
        ReactiveFormsModule,
        NgIf,
        MatFormFieldModule,
        MatSelectModule,
        NgForOf,
        IconButtonComponent,
        CircleButtonComponent,
    ],
})
export class AddEditDossierAttributeDialogComponent extends BaseDialogComponent implements OnDestroy {
    readonly dossierAttribute = this.data.dossierAttribute;
    readonly translations = dossierAttributeTypesTranslations;
    readonly typeOptions = Object.keys(DossierAttributeConfigTypes);
    readonly titleTranslateParams = {
        name: this.data.dossierAttribute?.label,
        type: this.data.dossierAttribute ? 'edit' : 'create',
    };

    get changed(): boolean {
        if (!this.dossierAttribute) {
            return true;
        }

        for (const key of Object.keys(this.form.getRawValue() as IDossierAttributeConfig)) {
            if (this.dossierAttribute[key] !== this.form.get(key).value) {
                return true;
            }
        }

        return false;
    }

    get #form() {
        const dossierAttribute = this.data.dossierAttribute;
        return this._formBuilder.group({
            label: [dossierAttribute?.label, Validators.required],
            ...(!!dossierAttribute && {
                placeholder: {
                    value: dossierAttribute.placeholder,
                    disabled: true,
                },
            }),
            type: [dossierAttribute?.type || FileAttributeConfigTypes.TEXT, Validators.required],
        });
    }

    constructor(
        private readonly _dossierAttributesService: DossierAttributesService,
        protected readonly _dialogRef: MatDialogRef<AddEditDossierAttributeDialogComponent>,
        @Inject(MAT_DIALOG_DATA) readonly data: AddEditDossierAttributeDialogData,
    ) {
        super(_dialogRef, !!data.dossierAttribute);
        this.form = this.#form;
        this.initialFormValue = this.form.getRawValue();
    }

    async save() {
        this._loadingService.start();

        const attribute: IDossierAttributeConfig = {
            id: this.dossierAttribute?.id,
            editable: true,
            ...this.form.getRawValue(),
        };

        const createOrUpdate = this._dossierAttributesService.createOrUpdate(attribute, this.data.dossierTemplateId);
        const result = await createOrUpdate.catch((error: HttpErrorResponse) => {
            this._loadingService.stop();
            this._toaster.error(_('add-edit-dossier-attribute.error.generic'), { error });
            return undefined;
        });

        if (result) {
            this._dialogRef.close(true);
        }
    }
}
