import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';
import { PreferencesKeys, UserPreferenceService } from '@users/user-preference.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { BaseFormComponent, IqserPermissionsService } from '@iqser/common-ui';
import { Roles } from '@users/roles';
import { AsControl } from '@iqser/common-ui/lib/utils';

interface PreferencesForm {
    // preferences
    autoExpandFiltersOnActions: boolean;
    displaySuggestionsInPreview: boolean;
    // warnings preferences
    unapprovedSuggestionsWarning: boolean;
    loadAllAnnotationsWarning: boolean;

    [k: string]: any;
}

type Screen = 'preferences' | 'warnings-preferences';

const Screens = {
    PREFERENCES: 'preferences',
    WARNING_PREFERENCES: 'warnings-preferences',
} as const;

@Component({
    selector: 'redaction-preferences',
    templateUrl: './preferences.component.html',
    styleUrls: ['./preferences.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PreferencesComponent extends BaseFormComponent {
    readonly form: FormGroup<AsControl<PreferencesForm>>;
    readonly currentScreen: Screen;
    readonly screens = Screens;
    initialFormValue: PreferencesForm;

    constructor(
        readonly userPreferenceService: UserPreferenceService,
        private readonly _formBuilder: FormBuilder,
        private readonly _permissionsService: IqserPermissionsService,
        private readonly _route: ActivatedRoute,
        private readonly _changeRef: ChangeDetectorRef,
    ) {
        super();
        this.form = this._formBuilder.group({
            // preferences
            autoExpandFiltersOnActions: [this.userPreferenceService.getAutoExpandFiltersOnActions()],
            displaySuggestionsInPreview: [this.userPreferenceService.getDisplaySuggestionsInPreview()],
            // warnings preferences
            unapprovedSuggestionsWarning: [this.userPreferenceService.getUnapprovedSuggestionsWarning()],
            loadAllAnnotationsWarning: [this.userPreferenceService.getBool(PreferencesKeys.loadAllAnnotationsWarning)],
        });

        if (!this._permissionsService.has(Roles.managePreferences)) {
            this.form.disable();
        }

        this.initialFormValue = this.form.getRawValue();
        this.currentScreen = _route.snapshot.data.screen;
    }

    async save(): Promise<any> {
        if (this.form.controls.autoExpandFiltersOnActions.value !== this.userPreferenceService.getAutoExpandFiltersOnActions()) {
            await this.userPreferenceService.toggleAutoExpandFiltersOnActions();
        }
        if (this.form.controls.displaySuggestionsInPreview.value !== this.userPreferenceService.getDisplaySuggestionsInPreview()) {
            await this.userPreferenceService.toggleDisplaySuggestionsInPreview();
        }
        if (this.form.controls.unapprovedSuggestionsWarning.value !== this.userPreferenceService.getUnapprovedSuggestionsWarning()) {
            await this.userPreferenceService.toggleUnapprovedSuggestionsWarning();
        }

        if (
            this.form.controls.loadAllAnnotationsWarning.value !==
            this.userPreferenceService.getBool(PreferencesKeys.loadAllAnnotationsWarning)
        ) {
            await this.userPreferenceService.save(
                PreferencesKeys.loadAllAnnotationsWarning,
                String(this.form.controls.loadAllAnnotationsWarning.value),
            );
        }

        await this.userPreferenceService.reload();
        this.form.patchValue({
            autoExpandFiltersOnActions: this.userPreferenceService.getAutoExpandFiltersOnActions(),
            displaySuggestionsInPreview: this.userPreferenceService.getDisplaySuggestionsInPreview(),
            unapprovedSuggestionsWarning: this.userPreferenceService.getUnapprovedSuggestionsWarning(),
        });
        this.initialFormValue = this.form.getRawValue();
        this._changeRef.markForCheck();
    }
}
