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

<div class="page-container">
  <app-page-header title="INVENTORY.COUNTS_TITLE" subtitle="INVENTORY.COUNTS_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_COUNT' | translate" icon="pi pi-plus" (onClick)="openNew()" />
  </app-page-header>

  <ng-template #bodyTpl let-item>
    <tr>
      <td class="mono">{{ item.count_number }}</td>
      <td>{{ item.date }}</td>
      <td>{{ item.warehouse_name || '—' }}</td>
      <td><p-tag [value]="item.status_label || item.status" [severity]="getStatusSeverity(item.status)" /></td>
      <td>
        @if (item.status === 'approved') {
          @if (getLinkedAdjustment(item.id); as adj) {
            @if (adj.status === 'draft') {
              <p-tag value="{{ 'INVENTORY.ADJ_PENDING' | translate }}" severity="warn" icon="pi pi-clock" />
            } @else if (adj.status === 'approved') {
              <p-tag value="{{ 'INVENTORY.ADJ_CONFIRMED' | translate }}" severity="success" icon="pi pi-check" />
            } @else if (adj.status === 'cancelled') {
              <p-tag value="{{ 'INVENTORY.ADJ_CANCELLED' | translate }}" severity="danger" icon="pi pi-times" />
            }
          } @else {
            <span class="text-muted">—</span>
          }
        } @else {
          <span class="text-muted">—</span>
        }
      </td>
      <td>
        <div class="action-buttons">
          <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="info" (onClick)="viewDetail(item)" [pTooltip]="'COMMON.VIEW' | translate" />
          @if (item.status === 'draft') {
            <p-button icon="pi pi-check" [rounded]="true" [text]="true" severity="success" (onClick)="finalize(item)" [pTooltip]="'INVENTORY.FINALIZE' | translate" />
            <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' && getLinkedAdjustment(item.id)?.status === 'draft') {
            <p-button icon="pi pi-check-circle" [rounded]="true" [text]="true" severity="warn" (onClick)="confirmAdjustment(item)" [pTooltip]="'INVENTORY.CONFIRM_ADJUSTMENT_BTN' | translate" styleClass="confirm-adj-btn" />
          }
        </div>
      </td>
    </tr>
  </ng-template>

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

<!-- ========== COUNT CREATE/EDIT DIALOG ========== -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editing() ? ('INVENTORY.EDIT_COUNT' | translate) : ('INVENTORY.NEW_COUNT' | 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-field">
      <label>{{ 'INVENTORY.NOTES' | translate }}</label>
      <textarea pTextarea formControlName="notes" rows="2"></textarea>
    </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.COUNTED_QUANTITY' | translate }} *</th>
            <th>{{ 'INVENTORY.UNIT_COST' | translate }} *</th>
            <th>{{ 'INVENTORY.NOTES' | 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-inputNumber formControlName="counted_quantity" [mode]="'decimal'" [minFractionDigits]="2" [style]="{width:'100px'}" /></td>
              <td><p-inputNumber formControlName="unit_cost" [mode]="'decimal'" [minFractionDigits]="2" [style]="{width:'100px'}" /></td>
              <td><input pInputText formControlName="notes" 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>

<!-- ========== COUNT DETAIL DIALOG ========== -->
<p-dialog [header]="'INVENTORY.COUNT_DETAIL' | translate" [(visible)]="detailDialogVisible" [modal]="true" [style]="{width:'750px'}">
  @if (detailItem()) {
    <div class="detail-view">
      <div class="detail-row"><strong>{{ 'INVENTORY.COUNT_NUMBER' | translate }}:</strong> <span class="mono">{{ detailItem()!.count_number }}</span></div>
      <div class="detail-row"><strong>{{ 'INVENTORY.DATE' | translate }}:</strong> {{ detailItem()!.date }}</div>
      <div class="detail-row"><strong>{{ 'INVENTORY.WAREHOUSE' | translate }}:</strong> {{ detailItem()!.warehouse_name }}</div>
      <div class="detail-row"><strong>{{ 'COMMON.STATUS' | translate }}:</strong> <p-tag [value]="detailItem()!.status_label || detailItem()!.status" [severity]="getStatusSeverity(detailItem()!.status)" /></div>
      @if (getLinkedAdjustment(detailItem()!.id); as adj) {
        <div class="detail-row">
          <strong>{{ 'INVENTORY.LINKED_ADJUSTMENT' | translate }}:</strong>
          <span class="mono">{{ adj.adjustment_number }}</span>
          <p-tag [value]="adj.status_label || adj.status" [severity]="getAdjStatusSeverity(adj)" style="margin-inline-start:0.5rem;" />
        </div>
      }
      @if (detailItem()!.notes) {
        <div class="detail-row"><strong>{{ 'INVENTORY.NOTES' | translate }}:</strong> {{ detailItem()!.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.SYSTEM_QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.COUNTED_QUANTITY' | translate }}</th>
              <th>{{ 'INVENTORY.DIFFERENCE' | translate }}</th>
              <th>{{ 'INVENTORY.UNIT_COST' | translate }}</th>
              <th>{{ 'INVENTORY.NOTES' | translate }}</th>
            </tr>
          </thead>
          <tbody>
            @for (line of detailItem()!.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.system_quantity | number:'1.2-2' }}</td>
                <td class="text-end">{{ line.counted_quantity | number:'1.2-2' }}</td>
                <td class="text-end" [class.text-danger]="line.difference < 0" [class.text-success]="line.difference > 0">{{ line.difference | number:'1.2-2' }}</td>
                <td class="text-end">{{ line.unit_cost | number:'1.2-2' }}</td>
                <td>{{ line.notes || '—' }}</td>
              </tr>
            }
          </tbody>
        </table>
      </div>
    </div>
  }
</p-dialog>
