import { computed, inject, Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { injectTabId } from '@isa/core/tabs';
import { ReturnTaskListStore } from '@isa/oms/data-access';
import { ReturnReviewComponent } from '../return-review.component';
import { injectConfirmationDialog } from '@isa/ui/dialog';

@Injectable({ providedIn: 'root' })
export class UncompletedTasksGuard
  implements CanDeactivate<ReturnReviewComponent>
{
  #returnTaskListStore = inject(ReturnTaskListStore);
  #confirmationDialog = injectConfirmationDialog();

  processId = injectTabId();

  uncompletedTaskListItems = computed(() => {
    const processId = this.processId();

    if (!processId) {
      return [];
    }

    const taskListItems = this.#returnTaskListStore.entityMap()[processId].data;

    if (!taskListItems || taskListItems?.length === 0) {
      return [];
    }

    return taskListItems.filter((item) => !item.completed);
  });

  canDeactivate(): boolean | Promise<boolean> {
    const hasUncompletedTasks = this.uncompletedTaskListItems().length > 0;

    if (!hasUncompletedTasks) {
      return true;
    }

    return this.openDialog();
  }

  async openDialog(): Promise<boolean> {
    const confirmDialogRef = this.#confirmationDialog({
      title: 'Aufgaben erledigen',
      data: {
        message:
          'Bitte schließen Sie die Aufgaben ab bevor Sie das die Rückgabe verlassen',
        closeText: 'Verlassen',
        confirmText: 'Zurück',
      },
    });

    const result = await firstValueFrom(confirmDialogRef.closed);
    return !result?.confirmed;
  }
}
