import { Component, Inject } from '@angular/core';
import { DefaultColorType } from '@red/domain';
import { BaseDialogComponent, IconButtonTypes } from '@iqser/common-ui';
import { UntypedFormGroup, Validators } from '@angular/forms';
import { defaultColorsTranslations } from '@translations/default-colors-translations';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { firstValueFrom } from 'rxjs';
import { DefaultColorsService } from '@services/entity-services/default-colors.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

interface IEditColorData {
    colorKey: DefaultColorType;
    dossierTemplateId: string;
}

@Component({
    templateUrl: './edit-color-dialog.component.html',
    styleUrls: ['./edit-color-dialog.component.scss'],
})
export class EditColorDialogComponent extends BaseDialogComponent {
    readonly iconButtonTypes = IconButtonTypes;
    readonly translations = defaultColorsTranslations;

    constructor(
        private readonly _defaultColorsService: DefaultColorsService,
        protected readonly _dialogRef: MatDialogRef<EditColorDialogComponent>,
        @Inject(MAT_DIALOG_DATA) readonly data: IEditColorData,
    ) {
        super(_dialogRef, true);

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

    async save() {
        const colors: Partial<Record<DefaultColorType, string>> = {
            [this.data.colorKey]: this.form.get('color').value,
        };

        this._loadingService.start();
        try {
            await firstValueFrom(this._defaultColorsService.update(colors, this.data.dossierTemplateId));
            this._dialogRef.close(true);
            this._loadingService.stop();
            this._toaster.info(_('edit-color-dialog.success'));
        } catch (e) {
            this._toaster.error(_('edit-color-dialog.error'));
        }
        this._loadingService.stop();
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            color: [
                this._defaultColorsService.find(this.data.dossierTemplateId)[this.data.colorKey],
                [Validators.required, Validators.minLength(7)],
            ],
        });
    }
}
