import { Component, Inject } from '@angular/core';
import { UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { EarmarkOperation, EarmarkOperationPages } from '@red/domain';
import { BaseDialogComponent, DetailsRadioOption } from '@iqser/common-ui';
import { EarmarksService } from '@services/files/earmarks.service';
import { firstValueFrom } from 'rxjs';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { highlightsTranslations } from '@translations/highlights-translations';
import { Roles } from '@users/roles';

export interface HighlightActionData {
    readonly operation: EarmarkOperation;
    readonly color: string;
    readonly dossierId: string;
    readonly fileId: string;
    readonly highlights: AnnotationWrapper[];
    readonly pageNumber: number;
    readonly annotationsChanged?: () => Promise<void>;
}

@Component({
    templateUrl: './highlight-action-dialog.component.html',
})
export class HighlightActionDialogComponent extends BaseDialogComponent {
    readonly translations = highlightsTranslations;
    readonly roles = Roles;
    readonly #operation = this.data.operation;
    readonly options: DetailsRadioOption<EarmarkOperationPages>[] = [
        {
            label: highlightsTranslations[this.#operation].options[EarmarkOperationPages.THIS_PAGE].label,
            value: EarmarkOperationPages.THIS_PAGE,
            description: highlightsTranslations[this.#operation].options[EarmarkOperationPages.THIS_PAGE].description,
        },
        {
            label: highlightsTranslations[this.#operation].options[EarmarkOperationPages.ALL_PAGES].label,
            value: EarmarkOperationPages.ALL_PAGES,
            description: highlightsTranslations[this.#operation].options[EarmarkOperationPages.ALL_PAGES].description,
        },
    ];

    constructor(
        protected readonly _dialogRef: MatDialogRef<HighlightActionDialogComponent>,
        private readonly _textHighlightService: EarmarksService,
        @Inject(MAT_DIALOG_DATA) readonly data: HighlightActionData,
    ) {
        super(_dialogRef);
        this.form = this._getForm();
        this.initialFormValue = this.form.getRawValue();
    }

    async save(): Promise<void> {
        this._loadingService.start();
        const { dossierId, fileId, operation, highlights, pageNumber, color } = this.data;

        // !color means we are in bulk select mode, so we don't need to apply additional page filters
        const filteredHighlights =
            !color || this.form.get('option').value.value === EarmarkOperationPages.ALL_PAGES
                ? highlights
                : highlights.filter(h => h.pageNumber === pageNumber);

        const ids = filteredHighlights.map(h => h.id);
        await firstValueFrom(this._textHighlightService.performHighlightsAction(ids, dossierId, fileId, operation));
        if (this.data.annotationsChanged) {
            await this.data.annotationsChanged();
        }
        this._loadingService.stop();
        this._dialogRef.close(true);
    }

    private _getForm(): UntypedFormGroup {
        if (this.data.color) {
            return this._formBuilder.group({
                color: [{ value: this.data.color, disabled: true }, Validators.required],
                option: [this.options[0], Validators.required],
            });
        }
        return this._formBuilder.group({
            confirmation: [false, Validators.requiredTrue],
        });
    }
}
