import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { Router } from '@angular/router';
import { Employee } from '@msfa-models/employee.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { EmployeeService } from '@msfa-services/api/employee.service';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface DeleteEmployeeData {
  toDelete: Employee;
  lastDeleted: Employee;
}

@Component({
  selector: 'msfa-employee-delete',
  templateUrl: './employee-delete.component.html',
  styleUrls: ['./employee-delete.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EmployeeDeleteComponent {
  @Input() returnToEmployeeList = false;

  deleteEmployeeData$: Observable<DeleteEmployeeData> = combineLatest([
    this.employeeService.employeeToDelete$,
    this.employeeService.lastDeletedEmployee$,
  ]).pipe(
    map(([employeeToDelete, lastDeletedEmployee]) => {
      return {
        toDelete: employeeToDelete,
        lastDeleted: lastDeletedEmployee?.id === employeeToDelete?.id ? lastDeletedEmployee : null,
      };
    })
  );
  private _errorDuringDeletion$ = new BehaviorSubject<CustomError>(null);
  errorDuringDeletion$: Observable<CustomError> = this._errorDuringDeletion$.asObservable();

  getPrimaryButtonText(lastDeleted: Employee): string {
    return lastDeleted ? 'Stäng' : 'Ta bort';
  }

  getSecondaryButtonText(lastDeleted: Employee): string {
    return lastDeleted ? null : 'Avbryt';
  }

  constructor(private employeeService: EmployeeService, private router: Router) {}

  deleteEmployeeModelPrimaryClick(deleteEmployeeData: DeleteEmployeeData): void {
    const { lastDeleted, toDelete } = deleteEmployeeData;
    if (lastDeleted) {
      this.closeDeleteEmployeeModal();
      if (this.returnToEmployeeList) {
        void this.router.navigateByUrl('/administration/personal');
      }
      return;
    }

    const deleteEmployeeSubscription = this.employeeService.deleteEmployee(toDelete).subscribe({
      error: (error: CustomError) => {
        this._errorDuringDeletion$.next(error);
      },
      complete: () => {
        deleteEmployeeSubscription.unsubscribe();
      },
    });
  }

  closeDeleteEmployeeModal(): void {
    this.employeeService.setEmployeeToDelete(null);
    this._errorDuringDeletion$.next(null);
  }
}
