import { Component, Inject, OnInit } from '@angular/core';
import { ReactiveFormsModule, UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import {
    BaseDialogComponent,
    CircleButtonComponent,
    getConfig,
    HasScrollbarDirective,
    HelpButtonComponent,
    IconButtonComponent,
    IqserDenyDirective,
} 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';
import { Roles } from '@users/roles';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
    SelectedAnnotationsTableComponent,
    ValueColumn,
} from '../../components/selected-annotations-table/selected-annotations-table.component';
import { NgForOf, NgIf } from '@angular/common';
import { MatFormField } from '@angular/material/form-field';
import { MatOption, MatSelect, MatSelectTrigger } from '@angular/material/select';
import { MatTooltip } from '@angular/material/tooltip';
import { TranslateModule } from '@ngx-translate/core';

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

const DOCUMINE_LEGAL_BASIS = 'n-a.';

@Component({
    selector: 'redaction-force-annotation-dialog',
    templateUrl: './force-annotation-dialog.component.html',
    styleUrls: ['./force-annotation-dialog.component.scss'],
    standalone: true,
    imports: [
        ReactiveFormsModule,
        NgIf,
        SelectedAnnotationsTableComponent,
        MatFormField,
        MatSelectTrigger,
        MatSelect,
        MatOption,
        MatTooltip,
        HasScrollbarDirective,
        TranslateModule,
        IconButtonComponent,
        IqserDenyDirective,
        CircleButtonComponent,
        NgForOf,
        HelpButtonComponent,
    ],
})
export class ForceAnnotationDialogComponent extends BaseDialogComponent implements OnInit {
    readonly isDocumine = getConfig().IS_DOCUMINE;

    readonly tableColumns = [
        {
            label: 'Value',
            show: true,
        },
        {
            label: 'Type',
            show: true,
        },
    ];
    readonly tableData: ValueColumn[][] = this._data.annotations.map(redaction => [
        { label: redaction.value, show: true, bold: true },
        { label: redaction.typeLabel, show: true },
    ]);

    legalOptions: LegalBasisOption[] = [];
    protected readonly roles = Roles;

    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 isImageHint() {
        return this._data.annotations.every(annotation => annotation.IMAGE_HINT);
    }

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

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

    get dialogTitle(): string {
        return this.isImageHint
            ? _('manual-annotation.dialog.header.force-redaction-image-hint')
            : this.isHintDialog
              ? _('manual-annotation.dialog.header.force-hint')
              : _('manual-annotation.dialog.header.force-redaction');
    }

    async ngOnInit() {
        if (!this.isDocumine) {
            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());
    }

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

    #createForceRedactionRequest(): ILegalBasisChangeRequest {
        const request: ILegalBasisChangeRequest = {};

        request.legalBasis = !this.isDocumine ? this.form.get('reason').value.legalBasis : DOCUMINE_LEGAL_BASIS;
        request.comment = this.form.get('comment').value;

        return request;
    }
}
