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

<div class="warehouse-transfers-page">
  <app-page-header title="INVENTORY.TRANSFERS_TITLE" subtitle="INVENTORY.TRANSFERS_SUBTITLE" (refresh)="loadData()">
    <p-button [label]="'INVENTORY.NEW_TRANSFER' | translate" icon="pi pi-plus" (onClick)="openNew()" />
  </app-page-header>

  <ng-template #bodyTpl let-item>
    <tr>
      <td class="mono">{{ item.transfer_number }}</td>
      <td>{{ item.date }}</td>
      <td>{{ item.from_warehouse?.name || '—' }}</td>
      <td>{{ item.to_warehouse?.name || '—' }}</td>
      <td class="text-end">{{ item.total_quantity | 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-truck" [rounded]="true" [text]="true" severity="success" (onClick)="ship(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 === 'shipped') {
            <p-button icon="pi pi-check-circle" [rounded]="true" [text]="true" severity="success" (onClick)="openReceiveDialog(item)" pTooltip="استلام" />
            <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_TRANSFER' | translate) : ('INVENTORY.NEW_TRANSFER' | translate)"
  [saving]="saving()"
  [width]="'950px'"
  (save)="onSave()"
>
  <form [formGroup]="form" class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'INVENTORY.FROM_WAREHOUSE' | translate }} *</label>
        <p-select formControlName="from_warehouse_id" [options]="warehouses()" optionLabel="name" optionValue="id" [filter]="true" [placeholder]="'INVENTORY.SELECT_WAREHOUSE' | translate" />
      </div>
      <div class="form-field">
        <label>{{ 'INVENTORY.TO_WAREHOUSE' | translate }} *</label>
        <p-select formControlName="to_warehouse_id" [options]="warehouses()" optionLabel="name" optionValue="id" [filter]="true" [placeholder]="'INVENTORY.SELECT_WAREHOUSE' | translate" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'INVENTORY.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </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="barcode-row">
      <span class="pi pi-barcode barcode-icon"></span>
      <input #barcodeInput pInputText
        [ngModel]="barcodeValue()" (ngModelChange)="barcodeValue.set($event)"
        [ngModelOptions]="{standalone: true}"
        [placeholder]="'INVENTORY.SCAN_BARCODE' | translate"
        (keydown.enter)="onBarcodeScan($event)"
        [disabled]="barcodeLoading()"
        class="barcode-input" />
      @if (barcodeLoading()) { <i class="pi pi-spin pi-spinner"></i> }
    </div>
    <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.REQUESTED_QUANTITY' | 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:'120px'}" /></td>
              <td><p-inputNumber formControlName="requested_quantity" [mode]="'decimal'" [minFractionDigits]="2" [style]="{width:'120px'}" /></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.TRANSFER_DETAIL' | translate" [(visible)]="detailDialogVisible" [modal]="true" [style]="{width:'800px'}">
  @if (selectedTransfer()) {
    <div class="detail-view">
      <div class="detail-row"><strong>{{ 'INVENTORY.TRANSFER_NUMBER' | translate }}:</strong> <span class="mono">{{ selectedTransfer()!.transfer_number }}</span></div>
      <div class="detail-row"><strong>{{ 'INVENTORY.DATE' | translate }}:</strong> {{ selectedTransfer()!.date }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.FROM_WAREHOUSE' | translate }}:</strong> {{ selectedTransfer()!.from_warehouse?.name }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.TO_WAREHOUSE' | translate }}:</strong> {{ selectedTransfer()!.to_warehouse?.name }}</div>
      <div class="detail-row"><strong>{{ 'COMMON.STATUS' | translate }}:</strong> <p-tag [value]="selectedTransfer()!.status_label || selectedTransfer()!.status" [severity]="getStatusSeverity(selectedTransfer()!.status)" /></div>
      @if (selectedTransfer()!.shipped_at) {
        <div class="detail-row"><strong>{{ 'INVENTORY.SHIPPED_AT' | translate }}:</strong> {{ selectedTransfer()!.shipped_at }}</div>
      }
      @if (selectedTransfer()!.received_at) {
        <div class="detail-row"><strong>{{ 'INVENTORY.RECEIVED_AT' | translate }}:</strong> {{ selectedTransfer()!.received_at }}</div>
      }
      @if (selectedTransfer()!.notes) {
        <div class="detail-row"><strong>{{ 'INVENTORY.NOTES' | translate }}:</strong> {{ selectedTransfer()!.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.REQUESTED_QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.SHIPPED_QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.RECEIVED_QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.UNIT_COST' | translate }}</th>
            </tr>
          </thead>
          <tbody>
            @for (line of selectedTransfer()!.items; track line.id; let i = $index) {
              <tr>
                <td>{{ i + 1 }}</td>
                <td>{{ line.product?.name }} ({{ line.product?.code }})@if (line.product_variant) { <small class="variant-badge">{{ line.product_variant.name }}</small> }</td>
                <td>{{ line.unit?.name }}</td>
                <td class="text-end">{{ line.requested_quantity | number:'1.2-2' }}</td>
                <td class="text-end">{{ line.shipped_quantity | number:'1.2-2' }}</td>
                <td class="text-end">{{ line.received_quantity | number:'1.2-2' }}</td>
                <td class="text-end">{{ line.unit_cost | number:'1.2-2' }}</td>
              </tr>
            }
          </tbody>
          <tfoot>
            <tr>
              <td colspan="3"><strong>{{ 'INVENTORY.TOTAL' | translate }}</strong></td>
              <td class="text-end"><strong>{{ selectedTransfer()!.total_quantity | number:'1.2-2' }}</strong></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  }
</p-dialog>

<!-- Receive Dialog -->
<p-dialog [header]="'INVENTORY.RECEIVE_TRANSFER' | translate" [(visible)]="receiveDialogVisible" [modal]="true" [style]="{width:'700px'}">
  @if (receivingTransfer()) {
    <div class="detail-view">
      <div class="detail-row"><strong>{{ 'INVENTORY.TRANSFER_NUMBER' | translate }}:</strong> <span class="mono">{{ receivingTransfer()!.transfer_number }}</span></div>
      <div class="detail-row"><strong>{{ 'INVENTORY.FROM_WAREHOUSE' | translate }}:</strong> {{ receivingTransfer()!.from_warehouse?.name }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.TO_WAREHOUSE' | translate }}:</strong> {{ receivingTransfer()!.to_warehouse?.name }}</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.REQUESTED_QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.RECEIVED_QUANTITY' | translate }} *</th>
            </tr>
          </thead>
          <tbody>
            @for (item of receiveItems(); track item.transfer_item_id; let i = $index) {
              <tr>
                <td style="width:40px; text-align:center;">{{ i + 1 }}</td>
                <td>{{ item.product_name }}</td>
                <td class="text-end">{{ item.requested_quantity | number:'1.2-2' }}</td>
                <td>
                  <p-inputNumber [ngModel]="item.received_quantity" (ngModelChange)="updateReceivedQuantity(i, $event)" [mode]="'decimal'" [minFractionDigits]="2" [min]="0" [style]="{width:'120px'}" />
                </td>
              </tr>
            }
          </tbody>
        </table>
      </div>

      <div class="dialog-actions">
        <p-button [label]="'COMMON.CANCEL' | translate" severity="secondary" [outlined]="true" (onClick)="receiveDialogVisible.set(false)" />
        <p-button [label]="'INVENTORY.CONFIRM_RECEIVE' | translate" icon="pi pi-check" severity="success" [loading]="saving()" (onClick)="onReceive()" />
      </div>
    </div>
  }
</p-dialog>
