import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { UntypedFormGroup, Validators } from '@angular/forms';
import { JustificationsService } from '@services/entity-services/justifications.service';
import { Dossier } from '@red/domain';
import { BaseDialogComponent } from '@iqser/common-ui';
import { firstValueFrom } from 'rxjs';

export interface LegalBasisOption {
    label?: string;
    legalBasis?: string;
    description?: string;
}

@Component({
    templateUrl: './change-legal-basis-dialog.component.html',
})
export class ChangeLegalBasisDialogComponent extends BaseDialogComponent implements OnInit {
    legalOptions: LegalBasisOption[] = [];

    constructor(
        private readonly _justificationsService: JustificationsService,
        protected readonly _dialogRef: MatDialogRef<ChangeLegalBasisDialogComponent>,
        @Inject(MAT_DIALOG_DATA) private readonly _data: { annotations: AnnotationWrapper[]; dossier: Dossier },
    ) {
        super(_dialogRef, true);
        this.form = this._getForm();
    }

    get allRectangles(): boolean {
        return this._data.annotations.reduce((acc, a) => acc && a.rectangle, true);
    }

    async ngOnInit() {
        const data = await firstValueFrom(this._justificationsService.getForDossierTemplate(this._data.dossier.dossierTemplateId));

        this.legalOptions = data
            .map<LegalBasisOption>(lbm => ({
                legalBasis: lbm.reason,
                description: lbm.description,
                label: lbm.name,
            }))
            .sort((a, b) => a.label.localeCompare(b.label));

        this.form.patchValue({
            reason: this.legalOptions.find(option => option.legalBasis === this._data.annotations[0].legalBasis),
        });
        this.initialFormValue = this.form.getRawValue();
    }

    save() {
        this._dialogRef.close({
            legalBasis: this.form.get('reason').value.legalBasis,
            section: this.form.get('section').value,
            comment: this.form.get('comment').value,
            value: this.form.get('classification').value,
        });
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            reason: [null, Validators.required],
            comment: [null],
            classification: [this.allRectangles ? this._data.annotations[0].value : null],
            section: [this._data.annotations[0].section],
        });
    }
}
