<pngx-page-header
  title="Tasks"
  i18n-title
  info="Tasks shows detailed information about document consumption and system tasks."
  i18n-info
  [loading]="loading() && pagedTasks().length === 0"
  >
  <div class="btn-toolbar col col-md-auto align-items-center gap-2">
    <button class="btn btn-sm btn-outline-secondary me-2" (click)="clearSelection()" [hidden]="selectedTasks.size === 0">
      <i-bs name="x" class="me-1"></i-bs><ng-container i18n>Clear selection</ng-container>
    </button>
    <button class="btn btn-sm btn-outline-primary me-2" (click)="dismissTasks()" *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.PaperlessTask }" [disabled]="visibleTasks.length === 0">
      <i-bs name="check2-all" class="me-1"></i-bs>{{dismissButtonText}}
    </button>
    <button class="btn btn-sm btn-outline-primary me-2" (click)="dismissAllTasks()" *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.PaperlessTask }" [disabled]="totalTasks() === 0">
      <i-bs name="check2-all" class="me-1"></i-bs><ng-container i18n>Dismiss all</ng-container>
    </button>
    <div class="form-check form-switch mb-0 ms-2">
      <input id="autoRefreshSwitch" class="form-check-input" type="checkbox" role="switch" [(ngModel)]="autoRefreshEnabled">
      <label class="form-check-label" for="autoRefreshSwitch" i18n>Auto refresh</label>
    </div>
  </div>
</pngx-page-header>

<div class="task-controls mb-3 gap-3 btn-toolbar align-items-center" role="toolbar">
  <div class="task-view-scope btn-group btn-group-sm" role="group">
    <input
      type="radio"
      class="btn-check"
      [checked]="selectedSection === TaskSection.All"
      id="section-all"
      (click)="setSection(TaskSection.All)"
      (keydown)="setSection(TaskSection.All)" />
    <label class="btn btn-outline-primary" for="section-all">
      <ng-container i18n>All</ng-container>
    </label>
    @for (section of sections; track section) {
      <input
        type="radio"
        class="btn-check"
        [checked]="selectedSection === section"
        id="section-{{section}}"
        (click)="setSection(section)"
        (keydown)="setSection(section)" />
      <label class="btn btn-outline-primary d-flex flex-row align-items-center" for="section-{{section}}">
        {{ sectionLabel(section) }}
        @if (sectionCount(section) > 0) {
          <span class="badge ms-2" [class.bg-danger]="section === TaskSection.NeedsAttention" [class.bg-secondary]="section !== TaskSection.NeedsAttention">{{sectionCount(section)}}</span>
        }
      </label>
    }
  </div>

  <div class="d-flex align-items-center gap-2">
    <div class="text-muted"><ng-container i18n>Filter by</ng-container>:</div>

    <div ngbDropdown>
      <button class="btn btn-sm btn-outline-primary" ngbDropdownToggle>{{selectedTaskTypeLabel}}</button>
      <div class="dropdown-menu shadow" ngbDropdownMenu>
        <button ngbDropdownItem [class.active]="selectedTaskType === null" (click)="setTaskType(null)" i18n>All types</button>
        @for (option of taskTypeOptions; track option.value) {
          <button ngbDropdownItem [class.active]="selectedTaskType === option.value" [disabled]="isTaskTypeOptionDisabled(option.value)" (click)="setTaskType(option.value)">{{option.label}}</button>
        }
      </div>
    </div>
    <div ngbDropdown>
      <button class="btn btn-sm btn-outline-primary" ngbDropdownToggle>{{selectedTriggerSourceLabel}}</button>
      <div class="dropdown-menu shadow" ngbDropdownMenu>
        <button ngbDropdownItem [class.active]="selectedTriggerSource === null" (click)="setTriggerSource(null)" i18n>All sources</button>
        @for (option of triggerSourceOptions; track option.value) {
          <button ngbDropdownItem [class.active]="selectedTriggerSource === option.value" [disabled]="isTriggerSourceOptionDisabled(option.value)" (click)="setTriggerSource(option.value)">{{option.label}}</button>
        }
      </div>
    </div>
  </div>

  <div class="form-inline d-flex align-items-center flex-grow-1 task-search">
    <div class="input-group input-group-sm flex-fill w-auto flex-nowrap">
      <div ngbDropdown>
        <button class="btn btn-sm btn-outline-primary" ngbDropdownToggle>{{filterTargetName}}</button>
        <div class="dropdown-menu shadow" ngbDropdownMenu>
          @for (t of filterTargets; track t.id) {
            <button ngbDropdownItem [class.active]="filterTargetID === t.id" (click)="setFilterTarget(t.id)">{{t.name}}</button>
          }
        </div>
      </div>
      @if (filterText?.length) {
        <button class="btn btn-link btn-sm px-2 position-absolute top-0 end-0 z-10" (click)="resetFilter()" aria-label="Clear search" i18n-aria-label>
          <i-bs width="1em" height="1em" name="x"></i-bs>
        </button>
      }
      <label class="visually-hidden" for="taskSearch" i18n>Search tasks</label>
      <input #filterInput id="taskSearch" class="form-control form-control-sm" type="text"
        (keyup)="filterInputKeyup($event)"
        [(ngModel)]="filterText">
    </div>
  </div>

  @if (isFiltered) {
    <button class="btn btn-link py-0 ms-md-auto" (click)="resetFilters()">
      <i-bs width="1em" height="1em" name="x"></i-bs><small i18n>Reset filters</small>
    </button>
  }

  <ngb-pagination
    [pageSize]="pageSize"
    [collectionSize]="totalTasks()"
    [page]="page"
    [maxSize]="5"
    [rotate]="true"
    size="sm"
    aria-label="Tasks pagination"
    (pageChange)="setPage($event)">
  </ngb-pagination>
</div>

<ng-template let-tasks="tasks" let-section="section" #tasksTemplate>
  <div class="section-header d-flex align-items-center justify-content-between mb-2">
    <div>
      <h5 class="mb-0">{{ sectionLabel(section) }}</h5>
      <div class="small text-muted">
        <ng-container i18n>{tasks.length, plural, =1 {1 task} other {{{tasks.length}} tasks}}</ng-container>
      </div>
    </div>
  </div>

  <div class="card border table-responsive mb-3">
    <table class="table table-striped align-middle shadow-sm mb-0 tasks-table">
      <thead>
        <tr>
          <th scope="col" class="select-col">
            <div class="form-check">
              <input
                type="checkbox"
                class="form-check-input"
                [id]="'all-tasks-' + section"
                [disabled]="tasks.length === 0"
                [checked]="areAllSelected(tasks)"
                (click)="toggleSection(section, $event); $event.stopPropagation();"
                (keydown)="toggleSection(section, $event); $event.stopPropagation();" />
              <label class="form-check-label" for="all-tasks-{{section}}"><span class="visually-hidden">Check all</span></label>
            </div>
          </th>
          <th scope="col" class="name-col-header" i18n>Name</th>
          <th scope="col" class="d-none d-lg-table-cell created-col" i18n>Created</th>
          @if (sectionShowsResults(section)) {
            <th scope="col" class="d-none d-lg-table-cell results-col" i18n>Results</th>
          }
          <th scope="col" class="d-table-cell d-lg-none" i18n>Info</th>
          <th scope="col" class="actions-col" i18n>Actions</th>
        </tr>
      </thead>
      <tbody>
        @for (task of tasks; track task.id) {
          <tr (click)="toggleSelected(task); $event.stopPropagation();" (keydown)="toggleSelected(task); $event.stopPropagation();">
            <td class="select-col">
              <div class="form-check">
                <input
                  type="checkbox"
                  class="form-check-input"
                  id="task{{task.id}}"
                  [checked]="selectedTasks.has(task.id)"
                  (click)="toggleSelected(task); $event.stopPropagation();"
                  (keydown)="toggleSelected(task); $event.stopPropagation();" />
                <label class="form-check-label" for="task{{task.id}}"></label>
              </div>
            </td>
            <td class="overflow-auto name-col">
              <div>{{ taskDisplayName(task) }}</div>
              <div class="small text-muted">
                @if (taskShowsSeparateTypeLabel(task)) {
                  <span>{{ task.task_type_display }}</span>
                  <span class="mx-1">&bull;</span>
                }
                <span>{{ task.trigger_source_display }}</span>
              </div>
            </td>
            <td class="d-none d-lg-table-cell created-col">{{ task.date_created | customDate:'short' }}</td>
            @if (sectionShowsResults(section)) {
              <td class="d-none d-lg-table-cell results-col">
                @if (taskHasLongResultMessage(task)) {
                  <div class="result" (click)="expandTask(task); $event.stopPropagation();"
                    [ngbPopover]="resultPopover" popoverClass="shadow small mobile" triggers="mouseenter:mouseleave" container="body">
                    <span class="small d-none d-md-inline-block font-monospace text-muted">{{ taskResultPreview(task) }}</span>
                  </div>
                }
                @if (taskHasResultMessage(task) && !taskHasLongResultMessage(task)) {
                  <span class="small d-none d-md-inline-block font-monospace text-muted">{{ taskResultMessage(task) }}</span>
                }
                @if (duplicateDocumentId(task)) {
                  <div class="small text-warning-emphasis d-flex align-items-center gap-1 mt-1">
                    <i-bs class="lh-1" width="1em" height="1em" name="exclamation-triangle"></i-bs>
                    <span>{{ duplicateTaskLabel(task) }}</span>
                  </div>
                }
                <ng-template #resultPopover>
                  <pre class="small mb-0">{{ taskResultPopoverMessage(task) }}@if (taskResultMessageOverflowsPopover(task)) {
                    &hellip;
                  }</pre>
                  @if (taskResultMessageOverflowsPopover(task)) {
                    <br/><em>(<ng-container i18n>click for full output</ng-container>)</em>
                  }
                </ng-template>
              </td>
            }
            <td class="d-lg-none">
              <button class="btn btn-link" (click)="expandTask(task); $event.stopPropagation();" aria-label="View task details" i18n-aria-label>
                <i-bs width="1.2em" height="1.2em" name="info-circle"></i-bs>
              </button>
            </td>
            <td class="actions-col">
              <div class="btn-group" role="group">
                <button class="btn btn-sm btn-outline-secondary" (click)="dismissTask(task); $event.stopPropagation();" *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.PaperlessTask }">
                  <i-bs name="check" class="me-1"></i-bs><ng-container i18n>Dismiss</ng-container>
                </button>
                <ng-container *pngxIfPermissions="{ action: PermissionAction.View, type: PermissionType.Document }">
                  @if (task.related_document_ids?.[0]) {
                    <a class="btn btn-sm btn-outline-primary" [routerLink]="['/documents', task.related_document_ids[0]]" (click)="dismissTask(task)">
                      <i-bs name="file-text" class="me-1"></i-bs><ng-container i18n>Open Document</ng-container>
                    </a>
                  }
                </ng-container>
              </div>
            </td>
          </tr>
        <tr>
          <td class="px-2 py-0" [class.border-0]="expandedTask !== task.id" [attr.colspan]="sectionShowsResults(section) ? 5 : 4">
            <div #collapse="ngbCollapse" [ngbCollapse]="expandedTask !== task.id" class="task-detail-panel bg-darker small mb-0">
              <div class="p-2 p-lg-3 ms-lg-3">
                @if (taskHasResultMessage(task)) {
                  <div class="detail-section mb-3">
                    <div class="detail-label fs-7 fw-bold text-uppercase text-muted mb-1" i18n>Result message</div>
                    <pre class="detail-block border border-dark bg-body p-3 rounded-2 mb-0">{{ taskResultMessage(task) }}</pre>
                  </div>
                }

                @if (duplicateDocumentId(task); as duplicateDocumentId) {
                  <div class="detail-section mb-3">
                    <div class="detail-label fs-7 fw-bold text-uppercase text-muted mb-1" i18n>Duplicate</div>
                    <div class="detail-block border border-dark bg-body p-3 rounded-2 mb-0">
                      <div class="d-flex align-items-center justify-content-between gap-3">
                        <div class="text-break">{{ duplicateTaskLabel(task) }}</div>
                        <button
                          class="btn btn-sm btn-outline-primary"
                          type="button"
                          (click)="openDuplicateDocument(duplicateDocumentId)">
                          <ng-container i18n>Open</ng-container>
                        </button>
                      </div>
                    </div>
                  </div>
                }

                <div class="row g-3">
                  <div class="col-12 col-xl-6">
                    <div class="detail-section h-100">
                      <div class="detail-label fs-7 fw-bold text-uppercase text-muted mb-1" i18n>Input data</div>
                      <pre class="detail-block border border-dark bg-body p-3 rounded-2 mb-0">{{ task.input_data | json }}</pre>
                    </div>
                  </div>
                  <div class="col-12 col-xl-6">
                    <div class="detail-section h-100">
                      <div class="detail-label fs-7 fw-bold text-uppercase text-muted mb-1" i18n>Result data</div>
                      <pre class="detail-block border border-dark bg-body p-3 rounded-2 mb-0">{{ (task.result_data ?? {}) | json }}</pre>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </td>
        </tr>
      }
      </tbody>
    </table>
  </div>
</ng-template>

@if (visibleSections.length > 0) {
  @for (section of visibleSections; track section) {
    <div class="mb-4">
      <ng-container [ngTemplateOutlet]="tasksTemplate" [ngTemplateOutletContext]="{tasks: tasksForSection(section), section: section}"></ng-container>
    </div>
  }
} @else if (!loading() || pagedTasks().length > 0) {
  <div class="alert alert-secondary fst-italic" i18n>No tasks match the current filters.</div>
}
