import { NgForOf, NgIf } from '@angular/common';
import { Component, inject, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { MatDialogClose } from '@angular/material/dialog';
import { MatFormField } from '@angular/material/form-field';
import { MatOption, MatSelect, MatSelectTrigger } from '@angular/material/select';
import { MatTooltip } from '@angular/material/tooltip';
import { DetailsRadioOption } from '@common-ui/inputs/details-radio/details-radio-option';
import { DetailsRadioComponent } from '@common-ui/inputs/details-radio/details-radio.component';
import { CircleButtonComponent, HasScrollbarDirective, IconButtonComponent, IconButtonTypes, IqserDialogComponent } from '@iqser/common-ui';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { TranslateModule } from '@ngx-translate/core';
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 {
    SelectedAnnotationsTableComponent,
    ValueColumn,
} from '../../components/selected-annotations-table/selected-annotations-table.component';
import { getRedactOrHintOptions } from '../../utils/dialog-options';
import { RedactOrHintOption, RedactOrHintOptions, RedactRecommendationData, RedactRecommendationResult } from '../../utils/dialog-types';
import { LegalBasisOption } from '../manual-redaction-dialog/manual-annotation-dialog.component';

@Component({
    templateUrl: './redact-recommendation-dialog.component.html',
    styleUrl: './redact-recommendation-dialog.component.scss',
    standalone: true,
    imports: [
        ReactiveFormsModule,
        SelectedAnnotationsTableComponent,
        DetailsRadioComponent,
        MatFormField,
        NgIf,
        MatOption,
        NgForOf,
        MatTooltip,
        HasScrollbarDirective,
        IconButtonComponent,
        TranslateModule,
        CircleButtonComponent,
        MatDialogClose,
        MatSelectTrigger,
        MatSelect,
    ],
})
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],
    });

    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 },
    ]);

    constructor(
        private readonly _justificationsService: JustificationsService,
        private readonly _dictionaryService: DictionaryService,
    ) {
        super();
        this.options = getRedactOrHintOptions(this.#dossier, this.#applyToAllDossiers, this.data.isApprover, false, 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.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.dossierId, !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() {
        const sameType = this.data.annotations.every(annotation => annotation.type === this.firstEntry.type);
        this.#applyToAllDossiers = this.data.applyToAllDossiers ?? true;
        if (this.dictionaryRequest) {
            this.form.controls.dictionary.setValue(sameType ? this.firstEntry.type : null);
            return;
        }
        this.form.controls.dictionary.setValue(this.#manualRedactionTypeExists ? SuperTypes.ManualRedaction : null);
    }
}
