import { Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, UntypedFormGroup } from '@angular/forms';
import { DetailsRadioOption, IconButtonTypes, IqserDialogComponent } from '@iqser/common-ui';
import { tap } from 'rxjs/operators';
import { getRemoveRedactionOptions, RemoveAnnotationOptions, RemoveRedactionOption } from '../../utils/dialog-options';
import { RemoveRedactionData, RemoveRedactionResult } from '../../utils/dialog-types';

@Component({
    templateUrl: './remove-redaction-dialog.component.html',
    styleUrls: ['./remove-redaction-dialog.component.scss'],
})
export class RemoveRedactionDialogComponent extends IqserDialogComponent<
    RemoveRedactionDialogComponent,
    RemoveRedactionData,
    RemoveRedactionResult
> {
    readonly iconButtonTypes = IconButtonTypes;
    readonly options: DetailsRadioOption<RemoveRedactionOption>[];
    readonly recommendation;
    readonly hint: boolean;
    readonly redactedTexts: string[];
    form!: UntypedFormGroup;
    #applyToAllDossiers: boolean;

    constructor(private readonly _formBuilder: FormBuilder) {
        super();
        this.recommendation = this.data.redactions[0].isRecommendation;
        this.hint = this.data.redactions[0].hint;
        this.options = getRemoveRedactionOptions(this.data);
        this.redactedTexts = this.data.redactions.map(annotation => annotation.value);
        this.form = this.#getForm();
        this.#applyToAllDossiers = this.data.applyToAllDossiers ?? true;

        this.form
            .get('option')
            .valueChanges.pipe(
                tap(() => {
                    for (const option of this.options) {
                        if (option.extraOption) {
                            option.extraOption.checked = this.#applyToAllDossiers;
                        }
                    }
                }),
                takeUntilDestroyed(),
            )
            .subscribe();
    }

    get isFalsePositive(): boolean {
        return this.form.get('option').value.value === RemoveAnnotationOptions.FALSE_POSITIVE;
    }

    save(): void {
        this.close(this.form.getRawValue());
    }

    #getForm() {
        return this._formBuilder.group({
            comment: [null],
            option: [this.options[0]],
        });
    }
}
