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

<div class="stock-receipts-page">
  <app-page-header title="INVENTORY.RECEIPTS_TITLE" subtitle="INVENTORY.RECEIPTS_SUBTITLE" (refresh)="loadData()">
    @if (quickMode()) {
      <p-tag [value]="'INVENTORY.QUICK_MODE' | translate" severity="success" icon="pi pi-bolt" styleClass="quick-mode-badge" />
    } @else {
      <p-tag [value]="'INVENTORY.COMPLETE_MODE' | translate" severity="info" icon="pi pi-list-check" styleClass="complete-mode-badge" />
    }
    <p-button [label]="'INVENTORY.NEW_RECEIPT' | translate" icon="pi pi-plus" (onClick)="openNew()" />
  </app-page-header>

  <ng-template #bodyTpl let-item>
    <tr>
      <td class="mono">{{ item.receipt_number }}</td>
      <td>{{ item.date }}</td>
      <td>{{ item.warehouse_name || '—' }}</td>
      <td>{{ item.reference_type_label || item.reference_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_RECEIPT' | translate) : ('INVENTORY.NEW_RECEIPT' | translate)"
  [saving]="saving()"
  [width]="'950px'"
  (save)="onSave()"
>
  <form [formGroup]="form" class="dialog-form">
    @if (savingStep()) {
      <div class="saving-step-indicator">
        <i class="pi pi-spin pi-spinner"></i>
        <span>{{ savingStep() }}</span>
      </div>
    }
    <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.REFERENCE_TYPE' | translate }} *</label>
        <p-select formControlName="reference_type" [options]="referenceTypeOptions" optionLabel="label" optionValue="value" />
      </div>
      <div class="form-field">
        <label>{{ 'INVENTORY.SUPPLIER' | translate }}</label>
        <p-select formControlName="partner_id" [options]="partners()" optionLabel="name" optionValue="id" [filter]="true" [showClear]="true" [placeholder]="'INVENTORY.SELECT_SUPPLIER' | translate" />
      </div>
    </div>
    <div class="form-field">
      <label>{{ 'INVENTORY.NOTES' | translate }}</label>
      <textarea pTextarea formControlName="notes" rows="2"></textarea>
    </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.QUANTITY' | translate }} *</th>
            <th>{{ 'INVENTORY.UNIT_COST' | translate }} *</th>
            <th>{{ 'INVENTORY.TOTAL_COST' | translate }}</th>
            <th>{{ 'INVENTORY.BATCH_NUMBER' | 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>
                      @if (product.barcode) { <small class="product-barcode"><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>
                @if (getProductBarcode(item.get('product_id')?.value); as bc) {
                  <div class="row-barcode"><i class="pi pi-barcode"></i> {{ bc }}</div>
                }
              </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-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="batch_number" style="width:80px;" /></td>
              <td>
                <div class="action-buttons">
                  @if (item.get('tracking_type')?.value === 'serial') {
                    <p-button icon="pi pi-hashtag" [rounded]="true" [text]="true"
                      [severity]="getRowSerials(i).length === +(item.get('quantity')?.value || 0) ? 'success' : 'warn'"
                      size="small" (onClick)="openSerialDialog(i)"
                      [pTooltip]="'INVENTORY.SERIAL_NUMBERS' | translate" />
                    @if (getRowSerials(i).length > 0) {
                      <span class="serial-badge">{{ getRowSerials(i).length }}/{{ item.get('quantity')?.value | number:'1.0-0' }}</span>
                    }
                  }
                  @if (itemsArray.length > 1) {
                    <p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="removeItem(i)" />
                  }
                </div>
              </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>

<!-- Serial Numbers Dialog -->
<p-dialog
  [header]="'INVENTORY.SERIAL_NUMBERS' | translate"
  [(visible)]="serialDialogVisible"
  [modal]="true"
  [style]="{width:'600px', maxHeight:'80vh'}"
  [closable]="true">
  <div class="serial-dialog">
    <div class="serial-dialog-info">
      <span><strong>{{ 'INVENTORY.PRODUCT' | translate }}:</strong> {{ serialDialogProductName() }}</span>
      <span><strong>{{ 'INVENTORY.QUANTITY' | translate }}:</strong> {{ serialDialogQty() }}</span>
    </div>
    <div class="serial-dialog-table">
      <table>
        <thead>
          <tr>
            <th style="width:40px;">#</th>
            <th>{{ 'PRODUCTS.SERIAL_NUMBER' | translate }} *</th>
            <th>{{ 'PRODUCTS.EXPIRY_DATE' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (row of serialDialogRows(); track $index; let ri = $index) {
            <tr>
              <td style="text-align:center;">{{ ri + 1 }}</td>
              <td>
                <input pInputText [value]="row.serial_number"
                  (input)="updateSerialRow(ri, 'serial_number', $any($event.target).value)"
                  style="width:100%; font-family:monospace;" />
              </td>
              <td>
                <input pInputText type="date" [value]="row.expiry_date || ''"
                  (input)="updateSerialRow(ri, 'expiry_date', $any($event.target).value)"
                  style="width:100%;" />
              </td>
            </tr>
          }
        </tbody>
      </table>
    </div>
    <div class="serial-dialog-actions">
      <p-button [label]="'COMMON.CONFIRM' | translate" icon="pi pi-check" (onClick)="confirmSerialDialog()" />
      <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" [outlined]="true" (onClick)="serialDialogVisible.set(false)" />
    </div>
  </div>
</p-dialog>

<!-- Detail View Dialog -->
<p-dialog [header]="'INVENTORY.RECEIPT_DETAIL' | translate" [(visible)]="detailDialogVisible" [modal]="true" [style]="{width:'750px'}">
  @if (selectedReceipt()) {
    <div class="detail-view">
      <div class="detail-row"><strong>{{ 'INVENTORY.RECEIPT_NUMBER' | translate }}:</strong> <span class="mono">{{ selectedReceipt()!.receipt_number }}</span></div>
      <div class="detail-row"><strong>{{ 'INVENTORY.DATE' | translate }}:</strong> {{ selectedReceipt()!.date }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.WAREHOUSE' | translate }}:</strong> {{ selectedReceipt()!.warehouse_name }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.REFERENCE_TYPE' | translate }}:</strong> {{ selectedReceipt()!.reference_type_label }}</div>
      <div class="detail-row"><strong>{{ 'COMMON.STATUS' | translate }}:</strong> <p-tag [value]="selectedReceipt()!.status_label || selectedReceipt()!.status" [severity]="getStatusSeverity(selectedReceipt()!.status)" /></div>
      @if (selectedReceipt()!.partner_name) {
        <div class="detail-row"><strong>{{ 'INVENTORY.SUPPLIER' | translate }}:</strong> {{ selectedReceipt()!.partner_name }}</div>
      }
      @if (selectedReceipt()!.notes) {
        <div class="detail-row"><strong>{{ 'INVENTORY.NOTES' | translate }}:</strong> {{ selectedReceipt()!.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.QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.UNIT_COST' | translate }}</th>
              <th>{{ 'INVENTORY.TOTAL_COST' | translate }}</th>
              <th>{{ 'INVENTORY.BATCH_NUMBER' | translate }}</th>
            </tr>
          </thead>
          <tbody>
            @for (line of selectedReceipt()!.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 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.batch_number || '—' }}</td>
              </tr>
              @if ($any(line).serial_numbers?.length) {
                <tr>
                  <td></td>
                  <td colspan="6" style="background:#f8fafc; padding:0.25rem 0.5rem; white-space:normal;">
                    <span style="font-size:0.75rem; font-weight:700; color:#6366f1;"><i class="pi pi-hashtag"></i> </span>
                    @for (sn of $any(line).serial_numbers; track sn) {
                      <span class="serial-tag-view">{{ sn }}</span>
                    }
                  </td>
                </tr>
              }
            }
          </tbody>
          <tfoot>
            <tr>
              <td colspan="3"><strong>{{ 'INVENTORY.TOTAL' | translate }}</strong></td>
              <td class="text-end"><strong>{{ selectedReceipt()!.total_quantity | number:'1.2-2' }}</strong></td>
              <td></td>
              <td class="text-end"><strong>{{ selectedReceipt()!.total_cost | number:'1.2-2' }}</strong></td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  }
</p-dialog>
