import {
    ChangeDetectionStrategy,
    ChangeDetectorRef,
    Component,
    ElementRef,
    Input,
    OnChanges,
    OnInit,
    SimpleChanges,
    ViewChild,
} from '@angular/core';
import { PrimaryFileAttributeService } from '@services/primary-file-attribute.service';
import { Dossier, File, IFileAttributeConfig, TrashFile } from '@red/domain';
import { FileAttributesService } from '@services/entity-services/file-attributes.service';
import { combineLatest, map, ReplaySubject } from 'rxjs';
import { ContextComponent } from '@iqser/common-ui/lib/utils';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { MatTooltip } from '@angular/material/tooltip';
import { AsyncPipe, NgIf } from '@angular/common';
import { FileAttributeComponent } from '../../../dossier-overview/components/file-attribute/file-attribute.component';
import { FileStatsComponent } from '@shared/components/file-stats/file-stats.component';

interface FileNameColumnContext {
    primaryAttribute: IFileAttributeConfig;
}

@Component({
    selector: 'redaction-file-name-column',
    templateUrl: './file-name-column.component.html',
    styleUrls: ['./file-name-column.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [MatTooltip, NgIf, AsyncPipe, FileAttributeComponent, FileStatsComponent],
})
export class FileNameColumnComponent extends ContextComponent<FileNameColumnContext> implements OnInit, OnChanges {
    readonly #reloadAttribute = new ReplaySubject<void>(1);
    @ViewChild('filenameColumn', { static: true }) filenameColumn: ElementRef;
    @Input() file?: File | TrashFile;
    @Input() dossier: Dossier;
    @Input() dossierTemplateId: string;
    ocrByDefault: boolean;
    width: number;

    constructor(
        private readonly _fileAttributeService: FileAttributesService,
        private readonly _primaryFileAttributeService: PrimaryFileAttributeService,
        private readonly _dossierTemplateService: DossierTemplatesService,
        private readonly _changeDetectorRef: ChangeDetectorRef,
    ) {
        super();
    }

    ngOnInit(): void {
        this.ocrByDefault = this._dossierTemplateService.find(this.dossierTemplateId).ocrByDefault;
        const primaryAttribute$ = combineLatest([this._fileAttributeService.fileAttributesConfig$, this.#reloadAttribute]).pipe(
            map(() => this.#findPrimaryAttribute()),
        );
        super._initContext({ primaryAttribute: primaryAttribute$ });
        const _observer = new ResizeObserver((entries: ResizeObserverEntry[]) => {
            this.#updateItemWidth(entries[0]);
        });
        _observer.observe(this.filenameColumn.nativeElement);
    }

    ngOnChanges(changes: SimpleChanges): void {
        if (changes.file) {
            this.#reloadAttribute.next();
        }
    }

    get defaultFile() {
        return this.file as File;
    }

    #findPrimaryAttribute() {
        if (this.file.softDeletedTime) {
            const primaryAttribute = this._primaryFileAttributeService.getPrimaryFileAttributeValue(this.file, this.dossierTemplateId);
            return { label: primaryAttribute } as IFileAttributeConfig;
        }
        const fileAttributes = this._fileAttributeService.getFileAttributeConfig(this.dossierTemplateId);
        return fileAttributes?.fileAttributeConfigs.find(a => a.primaryAttribute);
    }

    #updateItemWidth(resizeObserverEntry: ResizeObserverEntry) {
        this.width = resizeObserverEntry.contentRect.width;
        this._changeDetectorRef.markForCheck();
    }
}
