<p-toast />
<p-confirmDialog />

<div class="approval-workflows-page">
  <app-page-header title="SALES.APPROVAL_WORKFLOWS" subtitle="SALES.TITLE" (refresh)="retry()">
  </app-page-header>

  <p-tabs [value]="activeTab()" (valueChange)="activeTab.set($any($event))">
    <p-tablist>
      <p-tab value="workflows">{{ 'SALES.WORKFLOWS' | translate }}</p-tab>
      <p-tab value="pending">{{ 'SALES.PENDING_APPROVALS' | translate }}</p-tab>
    </p-tablist>
    <p-tabpanels>
      <!-- ─── Workflows Tab ──────────────────────────── -->
      <p-tabpanel value="workflows">
        <div class="toolbar">
          <p-button
            [label]="'SALES.ADD_WORKFLOW' | translate"
            icon="pi pi-plus"
            (onClick)="openNewWorkflow()"
          />
        </div>

        <p-table
          [value]="workflows()"
          [loading]="workflowsLoading()"
          [paginator]="false"
          styleClass="p-datatable-sm p-datatable-striped"
        >
          <ng-template #header>
            <tr>
              <th>{{ 'COMMON.NAME' | translate }}</th>
              <th>{{ 'SALES.DOCUMENT_TYPE' | translate }}</th>
              <th>{{ 'SALES.LEVELS' | translate }}</th>
              <th>{{ 'SALES.ACTIVE' | translate }}</th>
              <th>{{ 'COMMON.ACTIONS' | translate }}</th>
            </tr>
          </ng-template>
          <ng-template #body let-wf>
            <tr>
              <td>{{ wf.name }}</td>
              <td>{{ getDocTypeLabel(wf.document_type) }}</td>
              <td>{{ wf.levels?.length || 0 }}</td>
              <td>
                <p-tag
                  [value]="wf.is_active ? ('COMMON.YES' | translate) : ('COMMON.NO' | translate)"
                  [severity]="wf.is_active ? 'success' : 'danger'"
                />
              </td>
              <td>
                <div class="action-buttons">
                  <p-button
                    icon="pi pi-pencil"
                    [rounded]="true"
                    [text]="true"
                    severity="info"
                    (onClick)="editWorkflow(wf)"
                    [pTooltip]="'COMMON.EDIT' | translate"
                  />
                  <p-button
                    icon="pi pi-trash"
                    [rounded]="true"
                    [text]="true"
                    severity="danger"
                    (onClick)="deleteWorkflow(wf)"
                    [pTooltip]="'COMMON.DELETE' | translate"
                  />
                </div>
              </td>
            </tr>
          </ng-template>
          <ng-template #emptymessage>
            <tr>
              <td colspan="5" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td>
            </tr>
          </ng-template>
        </p-table>
      </p-tabpanel>

      <!-- ─── Pending Approvals Tab ──────────────────── -->
      <p-tabpanel value="pending">
        <p-table
          [value]="pendingApprovals()"
          [loading]="pendingLoading()"
          [paginator]="false"
          styleClass="p-datatable-sm p-datatable-striped"
        >
          <ng-template #header>
            <tr>
              <th>{{ 'SALES.DOCUMENT_TYPE' | translate }}</th>
              <th>{{ 'SALES.DOCUMENT_ID' | translate }}</th>
              <th>{{ 'SALES.LEVEL' | translate }}</th>
              <th>{{ 'SALES.APPROVER' | translate }}</th>
              <th>{{ 'SALES.DATE' | translate }}</th>
              <th>{{ 'COMMON.ACTIONS' | translate }}</th>
            </tr>
          </ng-template>
          <ng-template #body let-log>
            <tr>
              <td>{{ log.document_type?.replace('_', ' ') }}</td>
              <td class="mono">#{{ log.document_id }}</td>
              <td>{{ log.level }}</td>
              <td>{{ log.user?.name || '-' }}</td>
              <td>{{ log.created_at | date:'shortDate' }}</td>
              <td>
                <div class="action-buttons">
                  <p-button
                    icon="pi pi-check"
                    [rounded]="true"
                    [text]="true"
                    severity="success"
                    (onClick)="approveLog(log)"
                    [pTooltip]="'SALES.APPROVE' | translate"
                  />
                  <p-button
                    icon="pi pi-times"
                    [rounded]="true"
                    [text]="true"
                    severity="danger"
                    (onClick)="rejectLog(log)"
                    [pTooltip]="'SALES.REJECT' | translate"
                  />
                </div>
              </td>
            </tr>
          </ng-template>
          <ng-template #emptymessage>
            <tr>
              <td colspan="6" class="text-center">{{ 'SALES.NO_PENDING_APPROVALS' | translate }}</td>
            </tr>
          </ng-template>
        </p-table>
      </p-tabpanel>
    </p-tabpanels>
  </p-tabs>
</div>

<!-- Workflow Dialog -->
<p-dialog
  [header]="(editingWorkflow() ? 'COMMON.EDIT' : 'COMMON.CREATE') | translate"
  [(visible)]="dialogVisible"
  [modal]="true"
  [style]="{ width: '700px' }"
  [closable]="true"
>
  <form [formGroup]="workflowForm" class="workflow-form">
    <div class="form-grid">
      <div class="field">
        <label>{{ 'COMMON.NAME' | translate }} *</label>
        <input pInputText formControlName="name" class="w-full" />
      </div>
      <div class="field">
        <label>{{ 'COMMON.NAME_AR' | translate }}</label>
        <input pInputText formControlName="name_ar" class="w-full" />
      </div>
      <div class="field">
        <label>{{ 'SALES.DOCUMENT_TYPE' | translate }} *</label>
        <p-select
          formControlName="document_type"
          [options]="documentTypes"
          optionLabel="label"
          optionValue="value"
          styleClass="w-full"
        />
      </div>
      <div class="field toggle-field">
        <label>{{ 'SALES.ACTIVE' | translate }}</label>
        <p-toggleSwitch formControlName="is_active" />
      </div>
    </div>

    <!-- Levels -->
    <div class="levels-section">
      <div class="levels-header">
        <h4>{{ 'SALES.APPROVAL_LEVELS' | translate }}</h4>
        <p-button icon="pi pi-plus" [rounded]="true" [text]="true" (onClick)="addLevel()" [pTooltip]="'SALES.ADD_LEVEL' | translate" />
      </div>
      <div formArrayName="levels">
        @for (lvl of levelsArray.controls; track lvl; let i = $index) {
          <div class="level-row" [formGroupName]="i">
            <span class="level-num">{{ i + 1 }}</span>
            <div class="level-fields">
              <div class="field">
                <label>{{ 'SALES.APPROVER_TYPE' | translate }}</label>
                <p-select
                  formControlName="approver_type"
                  [options]="approverTypes"
                  optionLabel="label"
                  optionValue="value"
                  styleClass="w-full"
                />
              </div>
              @if (lvl.get('approver_type')?.value === 'user') {
                <div class="field">
                  <label>{{ 'SALES.USER' | translate }}</label>
                  <p-select
                    formControlName="user_id"
                    [options]="(users$ | async) || []"
                    optionLabel="name"
                    optionValue="id"
                    [placeholder]="'COMMON.SELECT' | translate"
                    [filter]="true"
                    [showClear]="true"
                    styleClass="w-full"
                  />
                </div>
              }
              <div class="field">
                <label>{{ 'SALES.MIN_AMOUNT' | translate }}</label>
                <p-inputNumber formControlName="min_amount" [minFractionDigits]="2" styleClass="w-full" />
              </div>
              <div class="field">
                <label>{{ 'SALES.MAX_AMOUNT' | translate }}</label>
                <p-inputNumber formControlName="max_amount" [minFractionDigits]="2" styleClass="w-full" />
              </div>
            </div>
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="removeLevel(i)"
              [disabled]="levelsArray.length <= 1"
            />
          </div>
        }
      </div>
    </div>
  </form>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="dialogVisible.set(false)"
    />
    <p-button
      [label]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="onSaveWorkflow()"
      [loading]="saving()"
    />
  </ng-template>
</p-dialog>
