import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Feature } from '@msfa-enums/feature.enum';
import { environment } from '@msfa-environment';
import { PaginationParams } from '@msfa-models/api/params.model';
import { ReportsData } from '@msfa-models/report.model';
import { DeltagareApiService } from '@msfa-services/api/deltagare.api.service';
import { UiLinkButtonType } from '@ui/link-button/link-button-type.enum';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, shareReplay, switchMap } from 'rxjs/operators';

@Component({
  selector: 'msfa-deltagare-tab-reports',
  templateUrl: './deltagare-tab-reports.component.html',
  styleUrls: ['./deltagare-tab-reports.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeltagareTabReportsComponent {
  @Input() deltagareName: string;
  UiLinkButtonType = UiLinkButtonType;

  genomforandereferens$: Observable<number> = this.activatedRoute.params.pipe(
    map(({ genomforandeReferens }) => +genomforandeReferens)
  );

  private _reportsParams$ = new BehaviorSubject<PaginationParams>({ page: 1, limit: 20 });
  reportsData$: Observable<ReportsData> = this._reportsParams$.pipe(
    switchMap(params => this.fetchReports$(params)),
    shareReplay(1)
  );

  _activeFeatures: Feature[] = environment.activeFeatures;

  get signalButtonVisible(): boolean {
    return this._activeFeatures.includes(Feature.REPORTING_SIGNAL);
  }
  get periodiskRedovisningButtonVisible(): boolean {
    return this._activeFeatures.includes(Feature.REPORTING_PERIODISK_REDOVISNING);
  }
  get informativRapportButtonVisible(): boolean {
    return this._activeFeatures.includes(Feature.REPORTING_INFORMATIV_RAPPORT);
  }
  get slutredovisningButtonVisible(): boolean {
    return this._activeFeatures.includes(Feature.REPORTING_SLUTREDOVISNING);
  }

  constructor(private activatedRoute: ActivatedRoute, private deltagareApiService: DeltagareApiService) {}

  private fetchReports$(params: PaginationParams): Observable<ReportsData> {
    return this.genomforandereferens$.pipe(
      switchMap(genomforandeReferens => this.deltagareApiService.fetchReports$(genomforandeReferens, params))
    );
  }

  setNewPage(page: number): void {
    this._reportsParams$.next({ ...this._reportsParams$.getValue(), page });
  }
}
