import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';
import { Dossier, DossierStats, TrashFile, TrashItem, User } from '@red/domain';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { DossierStatsService } from '@services/dossiers/dossier-stats.service';
import { DossierNameColumnComponent, PartialDossier } from '@shared/components/dossier-name-column/dossier-name-column.component';
import { Observable } from 'rxjs';
import { getCurrentUser, InitialsAvatarComponent } from '@common-ui/users';
import { MatIcon } from '@angular/material/icon';
import { FileNameColumnComponent } from '@shared/components/file-name-column/file-name-column.component';
import { AsyncPipe, NgIf } from '@angular/common';
import { CircleButtonComponent } from '@iqser/common-ui';
import { RouterLink } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { DatePipe } from '@shared/pipes/date.pipe';

@Component({
    selector: 'redaction-trash-table-item [item]',
    templateUrl: './trash-table-item.component.html',
    styleUrls: ['./trash-table-item.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [
        MatIcon,
        FileNameColumnComponent,
        DossierNameColumnComponent,
        NgIf,
        InitialsAvatarComponent,
        CircleButtonComponent,
        AsyncPipe,
        RouterLink,
        DatePipe,
        TranslateModule,
    ],
})
export class TrashTableItemComponent implements OnChanges {
    @Input() item: TrashItem;
    @Output() restore = new EventEmitter<TrashItem[]>();
    @Output() hardDelete = new EventEmitter<TrashItem[]>();
    fileDossier$: Observable<Dossier>;
    dossierStats$: Observable<DossierStats>;
    readonly #currentUser = getCurrentUser<User>();

    constructor(
        private readonly _activeDossiersService: ActiveDossiersService,
        readonly dossierStatsService: DossierStatsService,
    ) {}

    file(item: TrashItem): TrashFile {
        return item as TrashFile;
    }

    dossier(item: TrashItem): PartialDossier {
        return item as unknown as PartialDossier;
    }

    ngOnChanges(): void {
        if (this.item.isFile) {
            this.fileDossier$ = this._activeDossiersService.getEntityChanged$(this.file(this.item).dossierId);
        }
        if (this.item.isDossier) {
            this.dossierStats$ = this.dossierStatsService.watch$(this.item.id);
        }
    }

    get canUserUpdateUnassignedDossier() {
        return this.#currentUser.isManager && !this.item.ownerId;
    }
}
