import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { SortOrder } from '@msfa-enums/sort-order.enum';
import { DeltagareCompact } from '@msfa-models/deltagare.model';
import { PaginationMeta } from '@msfa-models/pagination-meta.model';
import { Sort } from '@msfa-models/sort.model';
import { IconType } from '@msfa-enums/icon-type.enum';
import { ErrorSeverity } from '@msfa-enums/error-severity.enum';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'msfa-deltagare-list',
  templateUrl: './deltagare-list.component.html',
  styleUrls: ['./deltagare-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeltagareListComponent {
  @Input() deltagare: DeltagareCompact[];
  @Input() paginationMeta: PaginationMeta;
  @Input() sort: Sort<keyof DeltagareCompact>;
  @Output() sorted = new EventEmitter<keyof DeltagareCompact>();
  @Output() paginated = new EventEmitter<number>();
  handelserDialogDeltagare$ = new BehaviorSubject<DeltagareCompact | null>(null);

  handelserDialogIsOpen$ = this.handelserDialogDeltagare$.pipe(map(genomforandereferens => !!genomforandereferens));

  iconType = IconType;
  errorSeverity = ErrorSeverity;

  columnHeaders: { label: string; key: keyof DeltagareCompact }[] = [
    { label: 'Namn', key: 'fullName' },
    {
      label: 'Tjänst',
      key: 'tjanst',
    },
    {
      label: 'Utförande verksamhet',
      key: 'utforandeVerksamhet',
    },
    {
      label: 'Startdatum',
      key: 'startdatumAvrop',
    },
    {
      label: 'Slutdatum',
      key: 'slutdatumAvrop',
    },
    {
      label: 'Status',
      key: 'genomforandeReferens',
    },
  ];

  orderType = SortOrder;

  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;
  }

  handleSort(key: keyof DeltagareCompact): void {
    this.sorted.emit(key);
  }

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

  openHandelser(deltagareCompact: DeltagareCompact): void {
    this.handelserDialogDeltagare$.next(deltagareCompact);
  }

  closeHandelser(): void {
    this.handelserDialogDeltagare$.next(null);
  }
}
