import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { SortOrder } from '@msfa-enums/sort-order.enum';
import { EmployeeCompactResponse } from '@msfa-models/api/employee.response.model';
import { EmployeeCompact } from '@msfa-models/employee.model';
import { PaginationMeta } from '@msfa-models/pagination-meta.model';
import { Sort } from '@msfa-models/sort.model';

@Component({
  selector: 'msfa-employees-list',
  templateUrl: './employees-list.component.html',
  styleUrls: ['./employees-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EmployeesListComponent {
  @Input() employees: EmployeeCompact[];
  @Input() paginationMeta: PaginationMeta;
  @Input() employeesLoading: boolean;
  @Input() sort: Sort<keyof EmployeeCompactResponse>;
  @Output() sorted = new EventEmitter<keyof EmployeeCompactResponse>();
  @Output() paginated = new EventEmitter<number>();
  @Output() deleteEmployee = new EventEmitter<EmployeeCompact>();

  columnHeaders: { label: string; key: keyof EmployeeCompactResponse }[] = [
    { label: 'Namn', key: 'name' },
    {
      label: 'Tjänst',
      key: 'tjanst',
    },
    {
      label: 'Utförande verksamheter',
      key: 'utforandeVerksamhet',
    },
  ];

  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 EmployeeCompactResponse): void {
    this.sorted.emit(key);
  }

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

  emitDeleteEmployee(employee: EmployeeCompact): void {
    this.deleteEmployee.emit(employee);
  }
}
