import { ChangeDetectorRef, Component, computed, ElementRef, Input, OnInit, Optional, ViewChild } from '@angular/core';
import { DisableStopPropagationDirective, HelpModeService } from '@iqser/common-ui';
import { Debounce, trackByFactory } from '@iqser/common-ui/lib/utils';
import { Dossier, File, IFileAttributeConfig } from '@red/domain';
import { FileAttributesService } from '@services/entity-services/file-attributes.service';
import { MatTooltip } from '@angular/material/tooltip';
import { RouterLink } from '@angular/router';
import { FileStatsComponent } from '@shared/components/file-stats/file-stats.component';
import { InitialsAvatarComponent, IqserUsersModule } from '@common-ui/users';
import { FileAttributeComponent } from '../file-attribute/file-attribute.component';
import { FileWorkloadComponent } from '../table-item/file-workload/file-workload.component';
import { ProcessingIndicatorComponent } from '@shared/components/processing-indicator/processing-indicator.component';
import { FileActionsComponent } from '../../../shared-dossiers/components/file-actions/file-actions.component';
import { AsyncPipe, NgForOf, NgIf } from '@angular/common';

@Component({
    selector: 'redaction-workflow-item',
    templateUrl: './workflow-item.component.html',
    styleUrls: ['./workflow-item.component.scss'],
    standalone: true,
    imports: [
        MatTooltip,
        RouterLink,
        FileStatsComponent,
        IqserUsersModule,
        FileAttributeComponent,
        FileWorkloadComponent,
        ProcessingIndicatorComponent,
        FileActionsComponent,
        NgIf,
        DisableStopPropagationDirective,
        AsyncPipe,
        NgForOf,
        InitialsAvatarComponent,
    ],
})
export class WorkflowItemComponent implements OnInit {
    @ViewChild('actionsWrapper', { static: true }) private _actionsWrapper: ElementRef;
    width: number;
    readonly trackBy = trackByFactory();
    @Input({ required: true }) file: File;
    @Input({ required: true }) dossier: Dossier;
    @Input({ required: true }) displayedAttributes: IFileAttributeConfig[];

    constructor(
        readonly fileAttributesService: FileAttributesService,
        private readonly _changeRef: ChangeDetectorRef,
        @Optional() readonly helpModeService: HelpModeService,
    ) {}

    ngOnInit(): void {
        const _observer = new ResizeObserver((entries: ResizeObserverEntry[]) => {
            this._updateItemWidth(entries[0]);
        });
        _observer.observe(this._actionsWrapper.nativeElement);
    }

    @Debounce(30)
    private _updateItemWidth(entry: ResizeObserverEntry): void {
        this.width = entry.contentRect.width;
        this._changeRef.markForCheck();
    }
}
