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

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

  <p-tabs [value]="activeTab()" (valueChange)="activeTab.set($any($event))">
    <p-tablist>
      <p-tab value="commissions">{{ 'SALES.COMMISSIONS' | translate }}</p-tab>
      <p-tab value="rules">{{ 'SALES.COMMISSION_RULES' | translate }}</p-tab>
    </p-tablist>
    <p-tabpanels>
      <!-- ─── Commissions Tab ──────────────────────────── -->
      <p-tabpanel value="commissions">
        <div class="bulk-actions" *ngIf="selectedCommissions().length > 0">
          <p-button
            [label]="'SALES.BULK_APPROVE' | translate"
            icon="pi pi-check"
            severity="info"
            size="small"
            (onClick)="bulkApprove()"
          />
          <p-button
            [label]="'SALES.BULK_MARK_PAID' | translate"
            icon="pi pi-money-bill"
            severity="success"
            size="small"
            (onClick)="bulkMarkPaid()"
          />
          <span class="selected-count">{{ selectedCommissions().length }} {{ 'COMMON.SELECTED' | translate }}</span>
        </div>

        <ng-template #commBodyTpl let-comm>
          <tr>
            <td>
              <p-checkbox
                [binary]="true"
                [ngModel]="selectedCommissions().includes(comm)"
                (onChange)="toggleSelection(comm)"
              />
            </td>
            <td class="mono">{{ comm.invoice?.invoice_number || '-' }}</td>
            <td>{{ comm.salesperson?.name || '-' }}</td>
            <td>{{ comm.partner?.name || '-' }}</td>
            <td class="amount">{{ comm.invoice_total | number:'1.2-2' }}</td>
            <td class="amount">{{ comm.commission_rate }}%</td>
            <td class="amount">{{ comm.commission_amount | number:'1.2-2' }}</td>
            <td>
              <p-tag
                [value]="getStatusLabel(comm.status)"
                [severity]="getStatusSeverity(comm.status)"
              />
            </td>
            <td>
              <div class="action-buttons">
                @if (comm.status === 'pending') {
                  <p-button
                    icon="pi pi-check"
                    [rounded]="true"
                    [text]="true"
                    severity="info"
                    (onClick)="approveCommission(comm)"
                    [pTooltip]="'SALES.APPROVE' | translate"
                  />
                }
                @if (comm.status === 'approved') {
                  <p-button
                    icon="pi pi-money-bill"
                    [rounded]="true"
                    [text]="true"
                    severity="success"
                    (onClick)="markPaid(comm)"
                    [pTooltip]="'SALES.MARK_PAID' | translate"
                  />
                }
              </div>
            </td>
          </tr>
        </ng-template>

        <app-data-table
          [data]="commissions()"
          [lazy]="true"
          [totalRecords]="commTotal()"
          [first]="commFirst"
          [loading]="commLoading()"
          [rows]="commRows"
          (onLazyLoad)="onCommPageChange($event)"
          [columns]="commColumns"
          (retry)="retry()"
          [bodyTpl]="commBodyTpl"
        >
        </app-data-table>
      </p-tabpanel>

      <!-- ─── Rules Tab ──────────────────────────────── -->
      <p-tabpanel value="rules">
        <div class="rules-toolbar">
          <p-button
            [label]="'SALES.ADD_RULE' | translate"
            icon="pi pi-plus"
            (onClick)="openNewRule()"
          />
        </div>

        <p-table
          [value]="rules()"
          [loading]="rulesLoading()"
          [paginator]="false"
          [rows]="50"
          styleClass="p-datatable-sm p-datatable-striped"
        >
          <ng-template #header>
            <tr>
              <th>{{ 'SALES.SALESPERSON' | translate }}</th>
              <th>{{ 'SALES.CATEGORY' | translate }}</th>
              <th>{{ 'SALES.PRODUCT' | translate }}</th>
              <th>{{ 'SALES.TYPE' | translate }}</th>
              <th>{{ 'SALES.RATE' | translate }}</th>
              <th>{{ 'SALES.MIN_AMOUNT' | translate }}</th>
              <th>{{ 'SALES.PRIORITY' | translate }}</th>
              <th>{{ 'SALES.ACTIVE' | translate }}</th>
              <th>{{ 'COMMON.ACTIONS' | translate }}</th>
            </tr>
          </ng-template>
          <ng-template #body let-rule>
            <tr>
              <td>{{ rule.salesperson?.name || '-' }}</td>
              <td>{{ rule.category?.name || '-' }}</td>
              <td>{{ rule.product?.name || '-' }}</td>
              <td>{{ getRuleTypeLabel(rule.type) }}</td>
              <td class="amount">{{ rule.rate }}</td>
              <td class="amount">{{ rule.min_amount | number:'1.2-2' }}</td>
              <td>{{ rule.priority }}</td>
              <td>
                <p-tag
                  [value]="rule.is_active ? ('COMMON.YES' | translate) : ('COMMON.NO' | translate)"
                  [severity]="rule.is_active ? 'success' : 'danger'"
                />
              </td>
              <td>
                <div class="action-buttons">
                  <p-button
                    icon="pi pi-pencil"
                    [rounded]="true"
                    [text]="true"
                    severity="info"
                    (onClick)="editRule(rule)"
                    [pTooltip]="'COMMON.EDIT' | translate"
                  />
                  <p-button
                    icon="pi pi-trash"
                    [rounded]="true"
                    [text]="true"
                    severity="danger"
                    (onClick)="deleteRule(rule)"
                    [pTooltip]="'COMMON.DELETE' | translate"
                  />
                </div>
              </td>
            </tr>
          </ng-template>
          <ng-template #emptymessage>
            <tr>
              <td colspan="9" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td>
            </tr>
          </ng-template>
        </p-table>
      </p-tabpanel>
    </p-tabpanels>
  </p-tabs>
</div>

<!-- Rule Dialog -->
<p-dialog
  [header]="(editingRule() ? 'COMMON.EDIT' : 'COMMON.CREATE') | translate"
  [(visible)]="ruleDialogVisible"
  [modal]="true"
  [style]="{ width: '550px' }"
  [closable]="true"
>
  <form [formGroup]="ruleForm" class="rule-form">
    <div class="form-grid">
      <div class="field">
        <label>{{ 'SALES.SALESPERSON' | translate }}</label>
        <p-select
          formControlName="salesperson_id"
          [options]="(users$ | async) || []"
          optionLabel="name"
          optionValue="id"
          [placeholder]="'SALES.ALL_SALESPERSONS' | translate"
          [showClear]="true"
          [filter]="true"
          styleClass="w-full"
        />
      </div>
      <div class="field">
        <label>{{ 'SALES.PRODUCT' | translate }}</label>
        <p-select
          formControlName="product_id"
          [options]="searchedProducts()"
          optionValue="id"
          [filter]="true"
          [filterBy]="'name_ar,name_en,code,barcode'"
          (onFilter)="onProductSearch($event)"
          appendTo="body"
          [placeholder]="'SALES.ALL_PRODUCTS' | translate"
          [showClear]="true"
          styleClass="w-full"
          [loading]="searchLoading()">
          <ng-template #item let-product>
            <div style="display: flex; flex-direction: column; gap: 1px;">
              <small style="color: #94a3b8;">{{ product.category?.name_ar || '—' }}</small>
              <span>{{ product.name_ar }} <small style="color: #64748b;">({{ product.code }})</small></span>
              @if (product.barcode) { <small style="color: #94a3b8;"><i class="pi pi-barcode"></i> {{ product.barcode }}</small> }
            </div>
          </ng-template>
          <ng-template #selectedItem let-product>
            <span>{{ product.name_ar }}</span>
          </ng-template>
        </p-select>
      </div>
      <div class="field">
        <label>{{ 'SALES.TYPE' | translate }}</label>
        <p-select
          formControlName="type"
          [options]="ruleTypes"
          optionLabel="label"
          optionValue="value"
          styleClass="w-full"
        />
      </div>
      <div class="field">
        <label>{{ 'SALES.RATE' | translate }}</label>
        <p-inputNumber formControlName="rate" [minFractionDigits]="2" 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.PRIORITY' | translate }}</label>
        <p-inputNumber formControlName="priority" [min]="1" styleClass="w-full" />
      </div>
      <div class="field toggle-field">
        <label>{{ 'SALES.ACTIVE' | translate }}</label>
        <p-toggleSwitch formControlName="is_active" />
      </div>
    </div>
  </form>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="ruleDialogVisible.set(false)"
    />
    <p-button
      [label]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="onSaveRule()"
      [loading]="savingRule()"
    />
  </ng-template>
</p-dialog>
