import { ChangeDetectionStrategy, Component, Input, OnChanges } from '@angular/core';
import { Dossier, DossierStats } from '@red/domain';
import { BehaviorSubject, Observable } from 'rxjs';
import { DossierStatsService } from '@services/dossiers/dossier-stats.service';
import { switchMap } from 'rxjs/operators';
import { DossierNameColumnComponent } from '@shared/components/dossier-name-column/dossier-name-column.component';
import { InitialsAvatarComponent } from '@common-ui/users';
import { DossierStateComponent } from '@shared/components/dossier-state/dossier-state.component';
import { DossiersListingActionsComponent } from '../../../shared-dossiers/components/dossiers-listing-actions/dossiers-listing-actions.component';
import { AsyncPipe } from '@angular/common';
import { DatePipe } from '@shared/pipes/date.pipe';

@Component({
    selector: 'redaction-table-item [dossier]',
    templateUrl: './table-item.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [
        DossierNameColumnComponent,
        InitialsAvatarComponent,
        DossierStateComponent,
        DossiersListingActionsComponent,
        AsyncPipe,
        DatePipe,
    ],
})
export class TableItemComponent implements OnChanges {
    @Input() dossier!: Dossier;
    readonly stats$: Observable<DossierStats>;
    readonly #ngOnChanges$ = new BehaviorSubject<string>(undefined);

    constructor(readonly dossierStatsService: DossierStatsService) {
        this.stats$ = this.#ngOnChanges$.pipe(switchMap(dossierId => this.dossierStatsService.watch$(dossierId)));
    }

    ngOnChanges() {
        if (this.dossier) {
            this.#ngOnChanges$.next(this.dossier.id);
        }
    }
}
