import { ChangeDetectionStrategy, Component, HostListener, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { getConfig, HasScrollbarDirective, HelpButtonComponent, IconButtonComponent, IconButtonTypes } from '@iqser/common-ui';
import { IqserEventTarget } from '@iqser/common-ui/lib/utils';
import { Dictionary, DOSSIER_TEMPLATE_ID, ENTITY_TYPE } from '@red/domain';
import { DictionariesMapService } from '@services/entity-services/dictionaries-map.service';
import { PermissionsService } from '@services/permissions.service';
import { AddEditEntityComponent } from '@shared/components/add-edit-entity/add-edit-entity.component';
import { getCurrentUser } from '@users/user.service';
import { Observable } from 'rxjs';
import { MatIcon } from '@angular/material/icon';
import { AsyncPipe, NgIf } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';

@Component({
    selector: 'redaction-entity-info',
    templateUrl: './entity-info.component.html',
    styleUrls: ['./entity-info.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [
        HasScrollbarDirective,
        MatIcon,
        NgIf,
        TranslateModule,
        AsyncPipe,
        IconButtonComponent,
        AddEditEntityComponent,
        HelpButtonComponent,
    ],
})
export class EntityInfoComponent {
    @ViewChild(AddEditEntityComponent) private readonly _addEditEntityComponent: AddEditEntityComponent;
    readonly currentUser = getCurrentUser();
    readonly entity$: Observable<Dictionary>;
    readonly dossierTemplateId: string;
    readonly config = getConfig();
    readonly iconButtonTypes = IconButtonTypes;

    constructor(
        route: ActivatedRoute,
        dictionariesMapService: DictionariesMapService,
        readonly permissionsService: PermissionsService,
    ) {
        this.dossierTemplateId = route.parent.snapshot.paramMap.get(DOSSIER_TEMPLATE_ID);
        const entityType = route.parent.snapshot.paramMap.get(ENTITY_TYPE);
        this.entity$ = dictionariesMapService.watch$(this.dossierTemplateId, entityType);
    }

    get disabled(): boolean {
        return !this._addEditEntityComponent || this._addEditEntityComponent.form?.invalid || !this._addEditEntityComponent.changed;
    }

    async save(): Promise<void> {
        await this._addEditEntityComponent.save();
    }

    revert(): void {
        this._addEditEntityComponent.revert();
    }

    @HostListener('window:keydown.Enter', ['$event'])
    async onEnter(event: KeyboardEvent): Promise<void> {
        event?.stopImmediatePropagation();
        const node = (event.target as IqserEventTarget).localName;
        if (this._addEditEntityComponent.valid && !this.disabled && this._addEditEntityComponent.changed && node !== 'textarea') {
            await this.save();
        }
    }
}
