import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { ReportType } from '@msfa-enums/report-type.enum';
import { PaginationMeta } from '@msfa-models/pagination-meta.model';
import { Report } from '@msfa-models/report.model';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'msfa-reports-list',
  templateUrl: './reports-list.component.html',
  styleUrls: ['./reports-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ReportsListComponent {
  @Input() reports: Report[];
  @Input() paginationMeta: PaginationMeta;
  @Input() deltagareName?: string;
  @Output() paginated = new EventEmitter<number>();
  private _activeReportMotivation$ = new BehaviorSubject<Report | null>(null);

  columnHeaders: { label: string; key: keyof Report }[] = [
    {
      label: 'Typ av rapport',
      key: 'type',
    },
    {
      label: 'Inskickad datum',
      key: 'date',
    },
    {
      label: 'Status',
      key: 'status',
    },
    {
      label: 'Motivering',
      key: 'motivation',
    },
  ];

  get activeReportMotivation(): Report {
    return this._activeReportMotivation$.getValue();
  }

  get currentPage(): number {
    return this.paginationMeta?.page;
  }

  get totalPage(): number {
    return this.paginationMeta?.totalPage;
  }

  get count(): number {
    return this.paginationMeta?.count;
  }

  get currentResultStart(): number {
    return (this.currentPage - 1) * this.paginationMeta?.limit + 1;
  }

  get currentResultEnd(): number {
    const end = this.currentResultStart + this.paginationMeta?.limit - 1;
    return end < this.count ? end : this.count;
  }

  getReportLink(report: Report): string {
    switch (report.type) {
      case ReportType.GemensamPlanering:
        return `./gemensam-planering/${report.id}`;
      case ReportType.Franvaro:
        return `./franvarorapport/${report.id}`;
      case ReportType.Avvikelse:
        return `./avvikelserapport/${report.id}`;
      case ReportType.PeriodiskRedovisning:
        return `./periodisk-redovisning/${report.id}`;
      case ReportType.Slutredovisning:
        return `./slutredovisning/${report.id}`;
      case ReportType.Signal:
        return `./signal/${report.id}`;
      case ReportType.InformativRapport:
      case ReportType.InformativRedovisning:
        return `./informativ-rapport/${report.id}`;
      default:
        return null;
    }
  }

  emitNewPage(page: number): void {
    this.paginated.emit(page);
  }

  openMotivationDialog(report: Report): void {
    this._activeReportMotivation$.next(report);
  }

  closeMotivationDialog(): void {
    this._activeReportMotivation$.next(null);
  }
}
