import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { EmployeeEditRequest } from '@msfa-models/api/employee-edit.request.model';
import { Employee } from '@msfa-models/employee.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { Role } from '@msfa-models/role.model';
import { Tjanst } from '@msfa-models/tjanst.model';
import { UtforandeVerksamhet } from '@msfa-models/utforande-verksamhet.model';
import { EmployeeService } from '@msfa-services/api/employee.service';
import { TjanstService } from '@msfa-services/api/tjanst.service';
import { RoleService } from '@msfa-services/role.service';
import { UtforandeVerksamheterService } from '@msfa-services/utforande-verksamheter/utforande-verksamheter.service';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { catchError, mapTo, startWith, switchMap } from 'rxjs/operators';

@Component({
  selector: 'msfa-employee-form',
  templateUrl: './employee-form.component.html',
  styleUrls: ['./employee-form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EmployeeFormComponent implements OnInit {
  private _employeeId$ = new BehaviorSubject<string>(this.activatedRoute.snapshot.params['employeeId']);
  private _selectedTjanstIds$ = new BehaviorSubject<number[]>(null);
  private _errorWhileUpdating$ = new BehaviorSubject<CustomError>(null);

  availableUtforandeVerksamheter$: Observable<UtforandeVerksamhet[]> = this._selectedTjanstIds$.pipe(
    switchMap(selectedTjanstIds => this.utforandeVerksamheterService.fetchUtforandeVerksamheter$(selectedTjanstIds))
  );

  errorWhileUpdating$: Observable<CustomError> = this._errorWhileUpdating$.asObservable();
  employee$ = this.employeeService.employee$;
  tjanster$: Observable<Tjanst[]> = this.tjanstService.tjanster$;
  availableRoles: Role[] = this.roleService.allRoles;

  isLoadingUtforandeVerksamheter$: Observable<boolean>;

  constructor(
    private employeeService: EmployeeService,
    private roleService: RoleService,
    private tjanstService: TjanstService,
    private utforandeVerksamheterService: UtforandeVerksamheterService,
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {}

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

  ngOnInit(): void {
    this.employeeService.setCurrentEmployeeId(this.employeeId);
  }

  updateEmployee(employeeFormData: EmployeeEditRequest): void {
    const updateEmployeeSubscription = this.employeeService
      .updateEmployee$(this.employeeId, employeeFormData)
      .subscribe({
        next: () => {
          void this.router.navigateByUrl(`/administration/personal/${this.employeeId}`);
        },
        error: error => {
          this._errorWhileUpdating$.next(error);
        },
        complete: () => {
          updateEmployeeSubscription.unsubscribe();
        },
      });
  }

  setupAvailableUtforandeVerksamheter(selectedTjanster: Tjanst[]): void {
    this._selectedTjanstIds$.next(selectedTjanster.map(tjanst => tjanst.tjanstId));
    this.isLoadingUtforandeVerksamheter$ = this.availableUtforandeVerksamheter$.pipe(
      mapTo(false),
      catchError(() => of(false)),
      startWith(true)
    );
  }
  setEmployeeToDelete(employee: Employee): void {
    this.employeeService.setEmployeeToDelete(employee);
  }

  closeError(): void {
    this._errorWhileUpdating$.next(null);
  }
}
