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

<div class="stock-adjustments-page">
  <app-page-header title="INVENTORY.ADJUSTMENTS_TITLE" subtitle="INVENTORY.ADJUSTMENTS_SUBTITLE" (refresh)="loadData()">
    <p-button [label]="'INVENTORY.NEW_ADJUSTMENT' | translate" icon="pi pi-plus" (onClick)="openNew()" />
  </app-page-header>

  <ng-template #bodyTpl let-item>
    <tr>
      <td class="mono">{{ item.adjustment_number }}</td>
      <td>{{ item.date }}</td>
      <td>{{ item.warehouse_name || '—' }}</td>
      <td>{{ item.adjustment_type_label || item.adjustment_type }}</td>
      <td class="text-end">{{ item.total_quantity | number:'1.2-2' }}</td>
      <td class="text-end">{{ item.total_cost | number:'1.2-2' }}</td>
      <td><p-tag [value]="item.status_label || item.status" [severity]="getStatusSeverity(item.status)" /></td>
      <td>
        <div class="action-buttons">
          <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="info" (onClick)="viewDetail(item)" pTooltip="عرض" />
          @if (item.status === 'draft') {
            <p-button icon="pi pi-check" [rounded]="true" [text]="true" severity="success" (onClick)="approve(item)" pTooltip="اعتماد" />
            <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" (onClick)="edit(item)" />
            <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="delete(item)" />
          }
          @if (item.status === 'approved') {
            <p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="danger" (onClick)="cancel(item)" pTooltip="إلغاء" />
          }
        </div>
      </td>
    </tr>
  </ng-template>

  <app-data-table
    [data]="items()"
    [loading]="loading()"
    [error]="null"
    (retry)="loadData()"
    [columns]="columns"
    [bodyTpl]="bodyTpl"
  />
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editing() ? ('INVENTORY.EDIT_ADJUSTMENT' | translate) : ('INVENTORY.NEW_ADJUSTMENT' | translate)"
  [saving]="saving()"
  [width]="'950px'"
  (save)="onSave()"
>
  <form [formGroup]="form" class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'INVENTORY.WAREHOUSE' | translate }} *</label>
        <p-select formControlName="warehouse_id" [options]="warehouses()" optionLabel="name" optionValue="id" [filter]="true" [placeholder]="'INVENTORY.SELECT_WAREHOUSE' | translate" />
      </div>
      <div class="form-field">
        <label>{{ 'INVENTORY.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'INVENTORY.ADJUSTMENT_TYPE' | translate }} *</label>
        <p-select formControlName="adjustment_type" [options]="adjustmentTypeOptions" optionLabel="label" optionValue="value" />
      </div>
      <div class="form-field">
        <label>{{ 'INVENTORY.NOTES' | translate }}</label>
        <textarea pTextarea formControlName="notes" rows="2"></textarea>
      </div>
    </div>

    <h4 class="section-title">{{ 'INVENTORY.ITEMS' | translate }}</h4>
    <div class="sub-table">
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>{{ 'INVENTORY.PRODUCT' | translate }} *</th>
            <th>{{ 'PRODUCTS.VARIANTS' | translate }}</th>
            <th>{{ 'INVENTORY.STOCK' | translate }}</th>
            <th>{{ 'INVENTORY.UNIT' | translate }} *</th>
            <th>{{ 'INVENTORY.ITEM_ADJ_TYPE' | translate }} *</th>
            <th>{{ 'INVENTORY.QUANTITY' | translate }} *</th>
            <th>{{ 'INVENTORY.UNIT_COST' | translate }} *</th>
            <th>{{ 'INVENTORY.TOTAL_COST' | translate }}</th>
            <th>{{ 'INVENTORY.REASON' | translate }}</th>
            <th></th>
          </tr>
        </thead>
        <tbody formArrayName="items">
          @for (item of itemsArray.controls; track item; let i = $index) {
            <tr [formGroupName]="$index">
              <td style="width:40px; text-align:center;">{{ i + 1 }}</td>
              <td>
                <p-select formControlName="product_id"
                  [options]="searchedProducts()"
                  optionValue="id"
                  [filter]="true"
                  [filterBy]="'name_ar,name_en,code,barcode'"
                  (onFilter)="onProductSearch($event)"
                  appendTo="body"
                  [style]="{width:'200px'}"
                  [placeholder]="'INVENTORY.SEARCH_PRODUCT' | translate"
                  [loading]="searchLoading()"
                  (onChange)="onProductChange(i, $event.value)">
                  <ng-template #item let-product>
                    <div class="product-option">
                      <small class="product-category">{{ product.category?.name_ar || '—' }}</small>
                      <span class="product-name">{{ product.name_ar }} <small class="product-code">({{ product.code }})</small></span>
                    </div>
                  </ng-template>
                  <ng-template #selectedItem let-product>
                    <span>{{ product.name_ar }}</span>
                  </ng-template>
                </p-select>
              </td>
              <td>
                @if (isVariantProduct(item.get('product_id')?.value)) {
                  <p-select formControlName="product_variant_id" [options]="getProductVariants(item.get('product_id')?.value)" optionLabel="name" optionValue="id" [filter]="true" appendTo="body" [style]="{width:'120px'}" [placeholder]="'—'" />
                }
              </td>
              <td class="stock-qty-cell">
                @if (getStockQty(item.get('product_id')?.value, item.get('product_variant_id')?.value) !== null) {
                  <span class="stock-badge" [class.stock-zero]="getStockQty(item.get('product_id')?.value, item.get('product_variant_id')?.value) === 0"
                    [class.stock-low]="getStockQty(item.get('product_id')?.value, item.get('product_variant_id')?.value)! > 0 && getStockQty(item.get('product_id')?.value, item.get('product_variant_id')?.value)! < 5">
                    {{ getStockQty(item.get('product_id')?.value, item.get('product_variant_id')?.value) | number:'1.2-2' }}
                  </span>
                }
              </td>
              <td><p-select formControlName="unit_id" [options]="(units$ | async) || []" optionLabel="name" optionValue="id" appendTo="body" [style]="{width:'100px'}" /></td>
              <td><p-select formControlName="adjustment_type" [options]="itemAdjTypeOptions" optionLabel="label" optionValue="value" appendTo="body" [style]="{width:'110px'}" /></td>
              <td><p-inputNumber formControlName="quantity" [mode]="'decimal'" [minFractionDigits]="2" [style]="{width:'80px'}" /></td>
              <td><p-inputNumber formControlName="unit_cost" [mode]="'decimal'" [minFractionDigits]="2" [style]="{width:'80px'}" /></td>
              <td class="mono text-end" style="min-width:70px;">{{ (item.get('quantity')?.value || 0) * (item.get('unit_cost')?.value || 0) | number:'1.2-2' }}</td>
              <td><input pInputText formControlName="reason" style="width:100px;" /></td>
              <td>
                @if (itemsArray.length > 1) {
                  <p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="removeItem(i)" />
                }
              </td>
            </tr>
          }
        </tbody>
      </table>
    </div>
    <div style="margin-top:0.5rem;">
      <p-button [label]="'INVENTORY.ADD_ITEM' | translate" icon="pi pi-plus" severity="secondary" [outlined]="true" size="small" (onClick)="addItem()" />
    </div>
  </form>
</app-form-dialog>

<!-- Detail View Dialog -->
<p-dialog [header]="'INVENTORY.ADJUSTMENT_DETAIL' | translate" [(visible)]="detailDialogVisible" [modal]="true" [style]="{width:'800px'}">
  @if (selectedAdjustment()) {
    <div class="detail-view">
      <div class="detail-row"><strong>{{ 'INVENTORY.ADJUSTMENT_NUMBER' | translate }}:</strong> <span class="mono">{{ selectedAdjustment()!.adjustment_number }}</span></div>
      <div class="detail-row"><strong>{{ 'INVENTORY.DATE' | translate }}:</strong> {{ selectedAdjustment()!.date }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.WAREHOUSE' | translate }}:</strong> {{ selectedAdjustment()!.warehouse_name }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.ADJUSTMENT_TYPE' | translate }}:</strong> {{ selectedAdjustment()!.adjustment_type_label || selectedAdjustment()!.adjustment_type }}</div>
      <div class="detail-row"><strong>{{ 'COMMON.STATUS' | translate }}:</strong> <p-tag [value]="selectedAdjustment()!.status_label || selectedAdjustment()!.status" [severity]="getStatusSeverity(selectedAdjustment()!.status)" /></div>
      @if (selectedAdjustment()!.notes) {
        <div class="detail-row"><strong>{{ 'INVENTORY.NOTES' | translate }}:</strong> {{ selectedAdjustment()!.notes }}</div>
      }
      <h4 class="section-title">{{ 'INVENTORY.ITEMS' | translate }}</h4>
      <div class="sub-table">
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>{{ 'INVENTORY.PRODUCT' | translate }}</th>
              <th>{{ 'INVENTORY.UNIT' | translate }}</th>
              <th>{{ 'INVENTORY.ITEM_ADJ_TYPE' | translate }}</th>
              <th>{{ 'INVENTORY.QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.UNIT_COST' | translate }}</th>
              <th>{{ 'INVENTORY.TOTAL_COST' | translate }}</th>
              <th>{{ 'INVENTORY.REASON' | translate }}</th>
            </tr>
          </thead>
          <tbody>
            @for (line of selectedAdjustment()!.items; track line.id; let i = $index) {
              <tr>
                <td>{{ i + 1 }}</td>
                <td>{{ line.product_name }} ({{ line.product_code }})@if (line.variant_name) { <small class="variant-badge">{{ line.variant_name }}</small> }</td>
                <td>{{ line.unit_name }}</td>
                <td>{{ line.adjustment_type_label || line.adjustment_type }}</td>
                <td class="text-end">{{ line.quantity | number:'1.2-2' }}</td>
                <td class="text-end">{{ line.unit_cost | number:'1.2-2' }}</td>
                <td class="text-end">{{ line.total_cost | number:'1.2-2' }}</td>
                <td>{{ line.reason || '—' }}</td>
              </tr>
            }
          </tbody>
          <tfoot>
            <tr>
              <td colspan="4"><strong>{{ 'INVENTORY.TOTAL' | translate }}</strong></td>
              <td class="text-end"><strong>{{ selectedAdjustment()!.total_quantity | number:'1.2-2' }}</strong></td>
              <td></td>
              <td class="text-end"><strong>{{ selectedAdjustment()!.total_cost | number:'1.2-2' }}</strong></td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  }
</p-dialog>
