import { Component, OnInit } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { CircleButtonComponent, HasScrollbarDirective, IconButtonComponent, IconButtonTypes, IqserDialogComponent } from '@iqser/common-ui';
import { Dictionary, Dossier, SuperTypes } from '@red/domain';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { Roles } from '@users/roles';
import { EditRedactionData, EditRedactResult } from '../../../utils/dialog-types';
import { SelectedAnnotationsListComponent } from '../../../components/selected-annotations-list/selected-annotations-list.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';
import { MatDialogClose } from '@angular/material/dialog';

@Component({
    templateUrl: 'edit-annotation-dialog.component.html',
    styleUrls: ['edit-annotation-dialog.component.scss'],
    standalone: true,
    imports: [
        ReactiveFormsModule,
        SelectedAnnotationsListComponent,
        NgIf,
        MatFormField,
        MatSelectTrigger,
        MatSelect,
        MatOption,
        NgForOf,
        MatTooltip,
        HasScrollbarDirective,
        TranslateModule,
        IconButtonComponent,
        CircleButtonComponent,
        MatDialogClose,
    ],
})
export class EditAnnotationDialogComponent
    extends IqserDialogComponent<EditAnnotationDialogComponent, EditRedactionData, EditRedactResult>
    implements OnInit
{
    readonly #dossier: Dossier;
    readonly roles = Roles;
    readonly iconButtonTypes = IconButtonTypes;
    readonly redactedTexts: string[];
    dictionaries: Dictionary[] = [];
    form: UntypedFormGroup;

    constructor(
        private readonly _activeDossiersService: ActiveDossiersService,
        private readonly _dictionaryService: DictionaryService,
        private readonly _formBuilder: FormBuilder,
    ) {
        super();
        this.#dossier = _activeDossiersService.find(this.data.dossierId);
        const annotations = this.data.annotations;
        this.redactedTexts = annotations.map(annotation => annotation.value);
        this.form = this.#getForm();
        this.initialFormValue = JSON.parse(JSON.stringify(this.form.getRawValue()));
    }

    get displayedDictionaryLabel() {
        const selectedDictionaryType = this.form.get('type').value;
        if (selectedDictionaryType) {
            return this.dictionaries.find(d => d.type === selectedDictionaryType)?.label ?? null;
        }
        return null;
    }

    get showList() {
        return this.data.annotations.every(annotation => annotation.isSkipped || annotation.isRedacted);
    }

    async ngOnInit(): Promise<void> {
        this.#setTypes();
    }

    reasonChanged() {
        this.form.patchValue({ reason: this.dictionaries.find(d => d.type === SuperTypes.ManualRedaction) });
    }

    save(): void {
        const value = this.form.value;
        this.dialogRef.close({
            comment: value.comment,
            type: value.type,
        });
    }

    #setTypes() {
        this.dictionaries = this._dictionaryService.getRedactionTypes(this.#dossier.dossierTemplateId);
    }

    #getForm(): UntypedFormGroup {
        const sameType = new Set(this.data.annotations.map(annotation => annotation.type)).size === 1;
        return this._formBuilder.group({
            comment: [null],
            type: [sameType ? this.data.annotations[0].type : null],
        });
    }

    #allRectangles() {
        return this.data.annotations.reduce((acc, a) => acc && a.AREA, true);
    }
}
