import { ChangeDetectionStrategy, Component, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Employee } from '@msfa-models/employee.model';
import { Role } from '@msfa-models/role.model';
import { EmployeeService } from '@msfa-services/api/employee.service';
import { RoleService } from '@msfa-services/role.service';
import { BehaviorSubject, Observable } from 'rxjs';

@Component({
  selector: 'msfa-employee-card',
  templateUrl: './employee-card.component.html',
  styleUrls: ['./employee-card.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EmployeeCardComponent implements OnDestroy {
  private _employeeId$ = new BehaviorSubject<string>(this.activatedRoute.snapshot.params['employeeId']);
  private _pendingSelectedParticipants$ = new BehaviorSubject<string[]>([]);
  employee$: Observable<Employee> = this.employeeService.employee$;
  lastUpdatedEmployeeId$: Observable<string> = this.employeeService.lastUpdatedEmployeeId$;
  allRoles: Role[] = this.roleService.allRoles;
  accordionsExpanded = [];

  constructor(
    private activatedRoute: ActivatedRoute,
    private employeeService: EmployeeService,
    private roleService: RoleService
  ) {
    this.employeeService.setCurrentEmployeeId(this.employeeId);
  }

  ngOnDestroy(): void {
    this.employeeService.resetLastUpdatedEmployeeId();
    this.employeeService.setCurrentEmployeeId(null);
  }

  get employeeId(): string {
    return this._employeeId$.getValue();
  }

  get pendingSelectedParticipants(): string[] {
    return this._pendingSelectedParticipants$.getValue();
  }

  isAccordionExpanded(id: number): boolean {
    return this.accordionsExpanded.includes(id);
  }

  closeUpdatedNotificationAlert(): void {
    this.employeeService.resetLastUpdatedEmployeeId();
  }

  toggleAccordionExpanded(currentId: number): void {
    if (this.accordionsExpanded.includes(currentId)) {
      this.accordionsExpanded = this.accordionsExpanded.filter(id => id !== currentId);
    } else {
      this.accordionsExpanded.push(currentId);
    }
  }
}
