import { booleanAttribute, ChangeDetectorRef, Component, Input, OnInit } from '@angular/core';
import { FormGroup, UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { BaseFormComponent, getConfig, LoadingService, Toaster } from '@iqser/common-ui';
import { Dictionary, IDictionary } from '@red/domain';
import { DictionariesMapService } from '@services/entity-services/dictionaries-map.service';
import { DictionaryService } from '@services/entity-services/dictionary.service';
import { toSnakeCase } from '@utils/functions';
import { firstValueFrom, Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

const REDACTION_FIELDS = ['defaultReason'];

interface Color {
    label: string;
    placeholder: string;
    controlName: string;
    hasColor$: Observable<boolean>;
    labelParams: () => Record<string, string>;
}

@Component({
    selector: 'redaction-add-edit-entity [entity] [dossierTemplateId]',
    templateUrl: './add-edit-entity.component.html',
    styleUrls: ['./add-edit-entity.component.scss'],
})
export class AddEditEntityComponent extends BaseFormComponent implements OnInit {
    @Input({ required: true }) dossierTemplateId: string;
    @Input({ required: true }) entity: Dictionary;
    @Input({ transform: booleanAttribute }) readOnly = false;
    @Input() dossierId?: string;

    technicalName$: Observable<string>;

    colors: Color[];
    readonly isDocumine = getConfig().IS_DOCUMINE;

    constructor(
        private readonly _dictionariesMapService: DictionariesMapService,
        private readonly _dictionaryService: DictionaryService,
        private readonly _toaster: Toaster,
        private readonly _loadingService: LoadingService,
        private readonly _formBuilder: UntypedFormBuilder,
        private readonly _changeRef: ChangeDetectorRef,
    ) {
        super();
    }

    get #isDossierRedaction(): boolean {
        return this.entity?.type === 'dossier_redaction';
    }

    get #isSystemManaged(): boolean {
        return !!this.entity?.systemManaged;
    }

    get #isHint(): boolean {
        return !!this.form.get('hint')?.value;
    }

    cpDisabled(color: Color) {
        return this.form.get(color.controlName).disabled;
    }

    revert(): void {
        this.form.patchValue(this.initialFormValue);
    }

    ngOnInit() {
        this.#initializeForm();
    }

    toggleDossierOnlyEntity() {
        const propName = 'dossierDictionaryOnly';
        const control = this.form.get(propName);
        if (control.disabled) {
            return;
        }
        this.form.patchValue({ [propName]: !control?.value });
    }

    async save(): Promise<void> {
        this._loadingService.start();
        const dictionary = this.#formToObject();
        try {
            if (this.entity) {
                // edit mode
                await firstValueFrom(
                    this._dictionaryService.updateDictionary(dictionary, this.dossierTemplateId, dictionary.type, this.dossierId),
                );
                this._toaster.success(_('add-edit-entity.success.edit'));
            } else {
                // create mode
                await firstValueFrom(this._dictionaryService.addDictionary({ ...dictionary, dossierTemplateId: this.dossierTemplateId }));
                this._toaster.success(_('add-edit-entity.success.create'));
            }
            this.initialFormValue = this.form.getRawValue();
            this._changeRef.markForCheck();
            this._loadingService.stop();
        } catch (e) {
            this._loadingService.stop();
            throw e;
        }
    }

    #initializeColors(form: FormGroup): void {
        this.colors = [
            {
                label: _('add-edit-entity.form.color'),
                labelParams: () => ({ type: this.#isHint ? 'hint' : 'redaction' }),
                placeholder: _('add-edit-entity.form.color-placeholder'),
                controlName: 'hexColor',
                hasColor$: this.#colorEmpty$(form, 'hexColor'),
            },
            {
                label: _('add-edit-entity.form.color'),
                labelParams: () => ({ type: 'recommendation' }),
                placeholder: _('add-edit-entity.form.color-placeholder'),
                controlName: 'recommendationHexColor',
                hasColor$: this.#colorEmpty$(form, 'recommendationHexColor'),
            },
            {
                label: _('add-edit-entity.form.color'),
                labelParams: () => ({ type: this.#isHint ? 'ignored' : 'skipped' }),
                placeholder: _('add-edit-entity.form.color-placeholder'),
                controlName: 'skippedHexColor',
                hasColor$: this.#colorEmpty$(form, 'skippedHexColor'),
            },
        ];
    }

    #initializeForm(): void {
        let controlsConfig: Record<string, any> = {
            label: [this.entity?.label, [Validators.required, Validators.minLength(3)]],
            hexColor: [this.entity?.hexColor, [Validators.required, Validators.minLength(7)]],
            recommendationHexColor: [this.entity?.recommendationHexColor, [Validators.required, Validators.minLength(7)]],
            skippedHexColor: [this.entity?.skippedHexColor, [Validators.required, Validators.minLength(7)]],
        };

        if (!this.#isDossierRedaction) {
            controlsConfig = {
                ...controlsConfig,
                type: [this.entity?.type],
                description: [this.entity?.description],
                rank: [{ value: this.entity?.rank, disabled: this.#isSystemManaged }, Validators.required],
                hint: [{ value: !!this.entity?.hint, disabled: this.#isSystemManaged }],
                hasDictionary: [{ value: !!this.entity?.hasDictionary, disabled: this.#isSystemManaged }],
                dossierDictionaryOnly: [{ value: !!this.entity?.dossierDictionaryOnly, disabled: this.#isSystemManaged || this.entity }],
                caseSensitive: [{ value: !!this.entity?.caseInsensitive, disabled: this.#isSystemManaged }],
                manageEntriesInDictionaryEditorOnly: [
                    {
                        value: !this.entity?.addToDictionaryAction,
                        disabled: this.#isSystemManaged && !this.#isDossierRedaction,
                    },
                ],
            };
        }

        if (!this.entity?.hint && !this.#isDossierRedaction) {
            controlsConfig = {
                ...controlsConfig,
                defaultReason: [{ value: null, disabled: true }],
            };
        }

        const form = this._formBuilder.group(controlsConfig);

        this.#initializeColors(form);
        this.technicalName$ = form.get('label').valueChanges.pipe(map((value: string) => this.#toTechnicalName(value)));

        if (!this.#isDossierRedaction) {
            form.get('hint').valueChanges.subscribe(isHint => {
                if (isHint) {
                    REDACTION_FIELDS.forEach(field => form.removeControl(field));
                } else {
                    form.addControl('defaultReason', new UntypedFormControl({ value: null, disabled: true }));
                }
            });

            if (!this.entity) {
                form.get('label').valueChanges.subscribe((label: string) => {
                    form.get('type').setValue(this.#toTechnicalName(label));
                });
            }
        }

        if (this.readOnly) {
            form.disable();
        }

        this.initialFormValue = form.getRawValue();

        this.form = form;
    }

    #toTechnicalName(value: string) {
        const existingTechnicalNames = this._dictionariesMapService.get(this.dossierTemplateId).map(dict => dict.type);
        const baseTechnicalName = toSnakeCase(value.trim());
        let technicalName = baseTechnicalName.replaceAll(/[^A-Za-z0-9_-]/g, '');
        if (!technicalName.length && baseTechnicalName.length) {
            technicalName = '_';
        }
        let suffix = 1;
        while (existingTechnicalNames.includes(technicalName)) {
            technicalName = technicalName === '_' ? `${technicalName}${suffix++}` : [technicalName, suffix++].join('_');
        }
        return technicalName;
    }

    #colorEmpty$(form: UntypedFormGroup, field: string) {
        return form.get(field).valueChanges.pipe(
            startWith(form.get(field).value),
            map((value: string) => !value || value?.length === 0),
        );
    }

    #formToObject(): IDictionary {
        // Fields which aren't set for hints, need additional check
        const addToDictionaryAction = !this.form.get('manageEntriesInDictionaryEditorOnly')?.value;
        const hasDictionary = !!this.form.get('hasDictionary')?.value;
        const dossierDictionaryOnly = !!this.form.get('dossierDictionaryOnly')?.value;

        const entity = {
            ...this.entity,
            label: this.form.get('label').value,
            hexColor: this.form.get('hexColor').value,
            recommendationHexColor: this.form.get('recommendationHexColor').value,
            skippedHexColor: this.form.get('skippedHexColor').value,
            dossierTemplateId: this.dossierTemplateId,
            addToDictionaryAction,
            dossierDictionaryOnly,
        };

        if (this.entity?.type !== 'dossier_redaction') {
            return {
                ...entity,
                type: this.form.get('type').value,
                description: this.form.get('description').value,
                hint: this.#isHint,
                rank: this.form.get('rank').value,
                caseInsensitive: !this.form.get('caseSensitive').value,
                hasDictionary,
            };
        }

        return entity;
    }
}
