import { Component, inject, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder } from '@angular/forms';
import { DetailsRadioOption, IconButtonTypes, IqserDialogComponent } from '@iqser/common-ui';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { Dictionary, IAddRedactionRequest, SuperTypes } from '@red/domain';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { JustificationsService } from '@services/entity-services/justifications.service';
import { firstValueFrom } from 'rxjs';
import { tap } from 'rxjs/operators';
import { getRedactOrHintOptions, RedactOrHintOption, RedactOrHintOptions } from '../../utils/dialog-options';
import { RedactRecommendationData, RedactRecommendationResult } from '../../utils/dialog-types';
import { LegalBasisOption } from '../manual-redaction-dialog/manual-annotation-dialog.component';

@Component({
    templateUrl: './redact-recommendation-dialog.component.html',
})
export class RedactRecommendationDialogComponent
    extends IqserDialogComponent<RedactRecommendationDialogComponent, RedactRecommendationData, RedactRecommendationResult>
    implements OnInit
{
    readonly #dossier = inject(ActiveDossiersService).find(this.data.dossierId);
    readonly #manualRedactionTypeExists = inject(DictionaryService).hasManualType(this.#dossier.dossierTemplateId);
    #applyToAllDossiers = this.data.applyToAllDossiers ?? true;
    readonly iconButtonTypes = IconButtonTypes;
    readonly options: DetailsRadioOption<RedactOrHintOption>[];
    readonly firstEntry = this.data.annotations[0];
    readonly isMulti = this.data.annotations.length > 1;
    dictionaryRequest = false;
    legalOptions: LegalBasisOption[] = [];
    dictionaries: Dictionary[] = [];
    readonly form = inject(FormBuilder).group({
        selectedText: this.isMulti ? null : this.firstEntry.value,
        comment: [null],
        dictionary: [null],
        option: [null],
        reason: [null],
    });

    constructor(
        private readonly _justificationsService: JustificationsService,
        private readonly _dictionaryService: DictionaryService,
    ) {
        super();
        this.options = getRedactOrHintOptions(this.#dossier, this.#applyToAllDossiers, this.data.isApprover, true);

        this.form.controls.option.valueChanges
            .pipe(
                tap((option: DetailsRadioOption<RedactOrHintOption>) => {
                    this.dictionaryRequest = option.value === RedactOrHintOptions.IN_DOSSIER;
                    this.#setDictionaries();
                    this.#resetValues();
                }),
                takeUntilDestroyed(),
            )
            .subscribe();

        this.form.controls.option.setValue(this.options[0]);
    }

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

    get disabled() {
        return this.dictionaryRequest && !this.form.controls.dictionary.value;
    }

    async ngOnInit(): Promise<void> {
        this.#setDictionaries();
        const data = await firstValueFrom(this._justificationsService.getForDossierTemplate(this.#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));
        this.#selectReason();
        this.#resetValues();
    }

    extraOptionChanged(option: DetailsRadioOption<RedactOrHintOption>): void {
        this.#applyToAllDossiers = option.extraOption.checked;

        this.#setDictionaries();
        if (this.#applyToAllDossiers && this.form.controls.dictionary.value) {
            const selectedDictionaryLabel = this.form.controls.dictionary.value;
            const selectedDictionary = this.dictionaries.find(d => d.type === selectedDictionaryLabel);
            if (!selectedDictionary) {
                this.form.controls.dictionary.setValue(null);
            }
        }
    }

    typeChanged() {
        if (!this.#applyToAllDossiers) {
            const selectedDictionaryType = this.form.controls.dictionary.value;
            const selectedDictionary = this.dictionaries.find(d => d.type === selectedDictionaryType);
            this.options[0].extraOption.disabled = selectedDictionary.dossierDictionaryOnly;
        }
    }

    save() {
        const redaction = this.#convertRecommendationToRedaction(this.firstEntry);
        this.close({
            redaction,
            isMulti: this.isMulti,
        });
    }

    #setDictionaries() {
        this.dictionaries = this._dictionaryService.getRedactTextDictionaries(this.#dossier.dossierTemplateId, !this.#applyToAllDossiers);
    }

    #selectReason() {
        if (this.legalOptions.length === 1) {
            this.form.controls.reason.setValue(this.legalOptions[0]);
        }
    }

    #convertRecommendationToRedaction(recommendation: AnnotationWrapper): IAddRedactionRequest {
        const addRedactionRequest: IAddRedactionRequest = { ...recommendation };
        addRedactionRequest.type = this.form.controls.dictionary.value;
        addRedactionRequest.value = this.form.controls.selectedText.value;

        const selectedType = this.dictionaries.find(d => d.type === addRedactionRequest.type);

        if (selectedType) {
            addRedactionRequest.addToDictionary = selectedType.hasDictionary;
        } else {
            addRedactionRequest.addToDictionary = this.dictionaryRequest && addRedactionRequest.type !== 'dossier_redaction';
        }

        const commentValue = this.form.controls.comment.value;
        addRedactionRequest.comment = commentValue ? { text: commentValue } : null;
        addRedactionRequest.addToAllDossiers = this.data.isApprover && this.dictionaryRequest && this.#applyToAllDossiers;
        return addRedactionRequest;
    }

    #resetValues() {
        this.#applyToAllDossiers = this.data.applyToAllDossiers ?? true;
        if (this.dictionaryRequest) {
            this.form.controls.dictionary.setValue(this.firstEntry.type);
            return;
        }
        this.form.controls.dictionary.setValue(this.#manualRedactionTypeExists ? SuperTypes.ManualRedaction : null);
    }
}
