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

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

@Component({
    selector: 'redaction-force-annotation-dialog',
    templateUrl: './force-annotation-dialog.component.html',
    styleUrls: ['./force-annotation-dialog.component.scss'],
})
export class ForceAnnotationDialogComponent extends BaseDialogComponent implements OnInit {
    readonly isDocumine = getConfig().IS_DOCUMINE;
    legalOptions: LegalBasisOption[] = [];

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

    get isHintDialog() {
        return this._data.hint;
    }

    get disabled(): boolean {
        return !this.valid;
    }

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

        this.legalOptions = data.map(lbm => ({
            legalBasis: lbm.reason,
            description: lbm.description,
            label: lbm.name,
        }));

        this.legalOptions.sort((a, b) => a.label.localeCompare(b.label));

        // Set pre-existing reason if it exists
        const existingReason = this.legalOptions.find(option => option.legalBasis === this._data.annotations[0].legalBasis);
        if (!this._data.hint && existingReason) {
            this.form.patchValue({ reason: existingReason }, { emitEvent: false });
        }

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

    save() {
        this._dialogRef.close(this._createForceRedactionRequest());
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            reason: this._data.hint ? ['Forced Hint'] : [null, Validators.required],
            comment: [null],
        });
    }

    private _createForceRedactionRequest(): ILegalBasisChangeRequest {
        const request: ILegalBasisChangeRequest = {};

        const legalOption: LegalBasisOption = this.form.get('reason').value;

        request.legalBasis = legalOption.legalBasis;
        request.comment = this.form.get('comment').value;

        return request;
    }
}
