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 { 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 { Roles } from '@users/roles';
import { calcTextWidthInPixels } from '@utils/functions';
import { firstValueFrom } from 'rxjs';
import { tap } from 'rxjs/operators';
import { getRedactOrHintOptions, RedactOrHintOption, RedactOrHintOptions } from '../../utils/dialog-options';
import { RedactTextData, RedactTextResult } from '../../utils/dialog-types';
import { LegalBasisOption } from '../manual-redaction-dialog/manual-annotation-dialog.component';

const MAXIMUM_SELECTED_TEXT_WIDTH = 421;

@Component({
    templateUrl: './redact-text-dialog.component.html',
    styleUrls: ['./redact-text-dialog.component.scss'],
})
export class RedactTextDialogComponent
    extends IqserDialogComponent<RedactTextDialogComponent, RedactTextData, RedactTextResult>
    implements OnInit
{
    readonly #dossier = inject(ActiveDossiersService).find(this.data.dossierId);
    readonly #manualRedactionTypeExists = inject(DictionaryService).hasManualType(this.#dossier.dossierTemplateId);
    #applyToAllDossiers = this.data.applyToAllDossiers ?? true;
    readonly roles = Roles;
    readonly iconButtonTypes = IconButtonTypes;
    readonly options = getRedactOrHintOptions(this.#dossier, this.#applyToAllDossiers, this.data.isApprover);
    readonly initialText = this.data?.manualRedactionEntryWrapper?.manualRedactionEntry?.value;
    readonly form = this.#getForm();
    dictionaryRequest = false;
    legalOptions: LegalBasisOption[] = [];
    dictionaries: Dictionary[] = [];
    isEditingSelectedText = false;
    modifiedText = this.initialText;
    selectedTextRows = 1;

    constructor(
        private readonly _justificationsService: JustificationsService,
        private readonly _dictionaryService: DictionaryService,
        private readonly _formBuilder: FormBuilder,
    ) {
        super();
        this.form.controls.option.valueChanges
            .pipe(
                tap((option: DetailsRadioOption<RedactOrHintOption>) => {
                    this.dictionaryRequest = option.value === RedactOrHintOptions.IN_DOSSIER;
                    if (this.dictionaryRequest) {
                        this.#setDictionaries();
                        this.form.patchValue({ selectedText: this.modifiedText });
                    } else {
                        this.isEditingSelectedText = false;
                        this.modifiedText = this.form.controls.selectedText.value;
                        this.form.patchValue({ selectedText: this.initialText });
                    }
                    this.#resetValues();
                }),
                takeUntilDestroyed(),
            )
            .subscribe();
    }

    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() {
        if (this.dictionaryRequest) {
            return !this.form.controls.dictionary.value;
        }
        return !this.form.controls.dictionary.value;
    }

    async ngOnInit(): Promise<void> {
        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();
    }

    undoTextChange() {
        this.form.patchValue({ selectedText: this.initialText });
    }

    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[1].extraOption.disabled = selectedDictionary.dossierDictionaryOnly;
        }
    }

    save(): void {
        this.#enhanceManualRedaction(this.data.manualRedactionEntryWrapper.manualRedactionEntry);
        const redaction = this.data.manualRedactionEntryWrapper.manualRedactionEntry;
        this.close({
            redaction,
            dictionary: this.dictionaries.find(d => d.type === this.form.controls.dictionary.value),
        });
    }

    toggleEditingSelectedText() {
        this.isEditingSelectedText = !this.isEditingSelectedText;
        if (this.isEditingSelectedText) {
            const width = calcTextWidthInPixels(this.form.controls.selectedText.value);
            this.selectedTextRows = Math.ceil(width / MAXIMUM_SELECTED_TEXT_WIDTH);
        }
    }

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

    #getForm() {
        return this._formBuilder.group({
            selectedText: this.data?.manualRedactionEntryWrapper?.manualRedactionEntry?.value,
            reason: null as LegalBasisOption,
            comment: [null],
            dictionary: [this.#manualRedactionTypeExists ? SuperTypes.ManualRedaction : null],
            option: this.options[0],
        });
    }

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

    #enhanceManualRedaction(addRedactionRequest: IAddRedactionRequest) {
        addRedactionRequest.type = this.form.controls.dictionary.value;
        addRedactionRequest.section = null;
        addRedactionRequest.value = this.form.controls.selectedText.value;

        const legalOption: LegalBasisOption = this.form.controls.reason.value;
        if (legalOption) {
            addRedactionRequest.reason = legalOption.description;
            addRedactionRequest.legalBasis = legalOption.legalBasis;
        }

        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';
        }

        if (!addRedactionRequest.reason) {
            addRedactionRequest.reason = 'Dictionary Request';
        }
        const commentValue = this.form.controls.comment.value;
        addRedactionRequest.comment = commentValue ? { text: commentValue } : null;
        addRedactionRequest.addToAllDossiers = this.data.isApprover && this.dictionaryRequest && this.#applyToAllDossiers;
    }

    #resetValues() {
        this.#applyToAllDossiers = this.data.applyToAllDossiers ?? true;
        this.options[1].extraOption.checked = this.#applyToAllDossiers;
        if (this.dictionaryRequest) {
            this.form.controls.reason.setValue(null);
            this.form.controls.dictionary.setValue(null);
            return;
        }
        this.form.controls.dictionary.setValue(this.#manualRedactionTypeExists ? SuperTypes.ManualRedaction : null);
    }
}
