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

<div class="invoices-page">
  <app-page-header title="SALES.INVOICES" subtitle="SALES.TITLE" (refresh)="retry()">
    <p-button
      [label]="'SALES.NEW_INVOICE' | translate"
      icon="pi pi-plus"
      (onClick)="openNew()"
    />
  </app-page-header>

  <!-- Quick Stats Bar -->
  <div class="stats-bar">
    <div class="stat-card outstanding">
      <div class="stat-icon"><i class="pi pi-wallet"></i></div>
      <div class="stat-info">
        <span class="stat-label">{{ 'SALES.TOTAL_OUTSTANDING' | translate }}</span>
        <span class="stat-value">{{ totalOutstanding() | number:'1.2-2' }}</span>
      </div>
    </div>
    <div class="stat-card overdue">
      <div class="stat-icon"><i class="pi pi-exclamation-triangle"></i></div>
      <div class="stat-info">
        <span class="stat-label">{{ 'SALES.OVERDUE_AMOUNT' | translate }}</span>
        <span class="stat-value">{{ overdueAmount() | number:'1.2-2' }}</span>
      </div>
    </div>
  </div>

  <ng-template #bodyTpl let-inv>
    <tr [class.overdue-row]="isOverdue(inv)">
      <td class="mono">{{ inv.invoice_number }}</td>
      <td>{{ inv.date }}</td>
      <td [class.text-danger]="isOverdue(inv)">
        {{ inv.due_date }}
        @if (isOverdue(inv)) {
          <i class="pi pi-exclamation-circle text-danger" style="margin-inline-start: 4px; font-size: 0.75rem;"></i>
        }
      </td>
      <td>{{ inv.customer_name }}</td>
      <td class="amount">{{ inv.total | number:'1.2-2' }}</td>
      <td class="amount">{{ inv.amount_paid | number:'1.2-2' }}</td>
      <td class="amount" [class.text-danger]="isOverdue(inv)">{{ inv.balance_due | number:'1.2-2' }}</td>
      <td>
        <p-tag
          [value]="getStatusLabel(inv.status)"
          [severity]="getStatusSeverity(inv.status)"
        />
      </td>
      <td>
        <p-tag
          [value]="getStatusLabel(inv.payment_status)"
          [severity]="getStatusSeverity(inv.payment_status)"
          [rounded]="true"
        />
      </td>
      <td>
        <div class="action-buttons">
          <p-button
            icon="pi pi-eye"
            [rounded]="true"
            [text]="true"
            severity="info"
            (onClick)="viewInvoice(inv)"
            [pTooltip]="'COMMON.VIEW' | translate"
          />
          @if (inv.status === 'draft') {
            <p-button
              icon="pi pi-pencil"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="editInvoice(inv)"
              [pTooltip]="'COMMON.EDIT' | translate"
            />
            @if (approvalWorkflow() === 'none') {
              <!-- No approval: post directly from draft -->
              <p-button
                icon="pi pi-check-circle"
                [rounded]="true"
                [text]="true"
                severity="success"
                (onClick)="postInvoice(inv)"
                [pTooltip]="'SALES.POST' | translate"
              />
            } @else {
              <!-- Approval required: submit for approval -->
              <p-button
                icon="pi pi-send"
                [rounded]="true"
                [text]="true"
                severity="warn"
                (onClick)="submitApproval(inv)"
                [pTooltip]="'SALES.SUBMIT_APPROVAL' | translate"
              />
            }
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="deleteInvoice(inv)"
              [pTooltip]="'COMMON.DELETE' | translate"
            />
          }
          @if (inv.status === 'pending_approval') {
            <p-button
              icon="pi pi-check"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="approveInvoice(inv)"
              [pTooltip]="'SALES.APPROVE' | translate"
            />
            <p-button
              icon="pi pi-times"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="rejectInvoice(inv)"
              [pTooltip]="'SALES.REJECT' | translate"
            />
          }
          @if (inv.status === 'approved') {
            <p-button
              icon="pi pi-check-circle"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="postInvoice(inv)"
              [pTooltip]="'SALES.POST' | translate"
            />
          }
          @if (inv.status === 'posted' || inv.status === 'partially_paid') {
            <p-button
              icon="pi pi-dollar"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="openPaymentDialog(inv)"
              [pTooltip]="'SALES.RECORD_PAYMENT' | translate"
            />
          }
          <p-button
            icon="pi pi-copy"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="duplicateInvoice(inv)"
            [pTooltip]="'SALES.DUPLICATE' | translate"
          />
          @if (inv.status !== 'cancelled' && inv.status !== 'paid') {
            <p-button
              icon="pi pi-ban"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="cancelInvoice(inv)"
              [pTooltip]="'SALES.CANCEL' | translate"
            />
          }
        </div>
      </td>
    </tr>
  </ng-template>

  <ng-template #filtersTpl>
    <app-sales-filter-bar
      [statusOptions]="statusOptions"
      [customers]="filterCustomers()"
      (filtersChange)="onFiltersChange($event)"
    />
  </ng-template>

  <app-data-table
    [data]="tableData()"
    [lazy]="true"
    [totalRecords]="totalRecords()"
    [first]="first"
    [loading]="tableLoading()"
    [rows]="rows"
    (onLazyLoad)="onPageChange($event)"
    [columns]="columns"
    (retry)="retry()"
    [bodyTpl]="bodyTpl"
    [filtersTpl]="filtersTpl"
  >
  </app-data-table>
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingInvoice() ? ('SALES.EDIT_INVOICE' | translate) : ('SALES.NEW_INVOICE' | translate)"
  width="80vw"
  [maximizable]="true"
  [saving]="saving()"
  [showFooter]="false"
>
  <form [formGroup]="invoiceForm" class="invoice-form compact">
    <!-- Compact header: Customer + Date + Due Date + optional fields inline -->
    <div class="form-strip">
      <div class="form-strip-field" style="min-width: 180px;">
        <label>
          {{ 'SALES.CUSTOMER' | translate }} *
          <p-button icon="pi pi-plus" [rounded]="true" [text]="true" size="small" severity="success"
            (onClick)="openQuickAddCustomer()" [pTooltip]="'SALES.ADD_CUSTOMER' | translate" />
          @if (customerBalanceLoading()) {
            <span class="customer-balance-badge loading"><i class="pi pi-spin pi-spinner"></i></span>
          } @else if (customerBalance() !== null && customerBalance()! > 0) {
            <span class="customer-balance-badge danger">
              <i class="pi pi-exclamation-triangle"></i> {{ customerBalance() | number:'1.0-0' }}
            </span>
          } @else if (customerBalance() !== null && customerBalance()! < 0) {
            <span class="customer-balance-badge success">
              <i class="pi pi-check-circle"></i> -{{ (customerBalance()! * -1) | number:'1.0-0' }}
            </span>
          }
        </label>
        <p-select
          formControlName="customer_id"
          [options]="searchedCustomers()"
          optionValue="id"
          [filter]="true"
          [filterBy]="'name,name_ar,name_en,code'"
          (onFilter)="onCustomerSearch($event)"
          (onChange)="onCustomerChange($event.value)"
          [placeholder]="'SALES.CUSTOMER' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
          [loading]="customerSearchLoading()"
        >
          <ng-template #selectedItem let-selected>
            <span>{{ selected.code }} - {{ selected.name }}</span>
          </ng-template>
          <ng-template #item let-partner>
            <span>{{ partner.code }} - {{ partner.name }}</span>
          </ng-template>
        </p-select>
      </div>
      <div class="form-strip-field">
        <label>{{ 'SALES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-strip-field">
        <label>{{ 'SALES.DUE_DATE' | translate }} *</label>
        <p-datepicker formControlName="due_date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      @if (isFieldVisible('warehouse')) {
        <div class="form-strip-field">
          <label>{{ 'SALES.WAREHOUSE' | translate }}</label>
          <p-select
            formControlName="warehouse_id"
            [options]="warehouses()"
            optionLabel="name"
            optionValue="id"
            [filter]="true"
            filterBy="name,name_en,code"
            [showClear]="true"
            [placeholder]="'SALES.WAREHOUSE' | translate"
            [style]="{ width: '100%' }"
            appendTo="body"
            (onChange)="onDefaultWarehouseChange($event.value)"
          >
            <ng-template #item let-wh>
              <span>{{ wh.name }} <small style="color: #94a3b8;">({{ wh.code }})</small></span>
            </ng-template>
            <ng-template #selectedItem let-wh>
              <span>{{ wh.name }}</span>
            </ng-template>
          </p-select>
        </div>
      }
      @if (isFieldVisible('price_type')) {
        <div class="form-strip-field">
          <label>{{ 'PRODUCTS.PRICE_TYPE' | translate }}</label>
          <p-select
            formControlName="price_type"
            [options]="priceTypeOptions"
            optionValue="value"
            [style]="{ width: '100%' }"
            appendTo="body"
            (onChange)="onPriceTypeChange($event.value)"
          >
            <ng-template #item let-opt>
              <span>{{ opt.label | translate }}</span>
            </ng-template>
            <ng-template #selectedItem let-opt>
              <span>{{ opt.label | translate }}</span>
            </ng-template>
          </p-select>
        </div>
      }
      <!-- Settings gear — always visible -->
      <div class="form-strip-field" style="max-width: 32px; align-self: flex-end;">
        <p-button icon="pi pi-cog" [rounded]="true" [text]="true" severity="secondary" size="small"
          (onClick)="fieldSettingsVisible.set(!fieldSettingsVisible())"
          [pTooltip]="'SETTINGS.TITLE' | translate" />
      </div>
    </div>

    <!-- Secondary strip: salesperson, payment terms, currency, reference -->
    @if (isFieldVisible('salesperson') || isFieldVisible('payment_terms') || isFieldVisible('currency')) {
      <div class="form-strip secondary">
        @if (isFieldVisible('salesperson')) {
          <div class="form-strip-field">
            <label>{{ 'SALES.SALESPERSON' | translate }}</label>
            <p-select
              formControlName="salesperson_id"
              [options]="(users$ | async) || []"
              optionLabel="name"
              optionValue="id"
              [filter]="true"
              filterBy="name,email"
              [showClear]="true"
              [placeholder]="'SALES.SALESPERSON' | translate"
              [style]="{ width: '100%' }"
              appendTo="body"
            />
          </div>
        }
        @if (isFieldVisible('payment_terms')) {
          <div class="form-strip-field" style="max-width: 120px;">
            <label>{{ 'SALES.PAYMENT_TERMS' | translate }}</label>
            <p-inputNumber formControlName="payment_terms_days" [min]="0" [style]="{ width: '100%' }" />
          </div>
        }
        @if (isFieldVisible('currency')) {
          <div class="form-strip-field" style="max-width: 120px;">
            <label>{{ 'SALES.CURRENCY' | translate }}</label>
            <p-select
              formControlName="currency_code"
              [options]="(currencies$ | async) || []"
              optionLabel="code"
              optionValue="code"
              [placeholder]="'SALES.CURRENCY' | translate"
              [style]="{ width: '100%' }"
              appendTo="body"
            />
          </div>
          <div class="form-strip-field" style="max-width: 120px;">
            <label>{{ 'SALES.EXCHANGE_RATE' | translate }}</label>
            <p-inputNumber formControlName="exchange_rate" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="6" [style]="{ width: '100%' }" />
          </div>
        }
        <div class="form-strip-field grow-2">
          <label>{{ 'SALES.REFERENCE' | translate }}</label>
          <input pInputText formControlName="reference" />
        </div>
      </div>
    }

    @if (fieldSettingsVisible()) {
      <div class="field-settings-panel">
        <div class="field-settings-grid">
          @for (f of [
            {key: 'warehouse', label: 'SALES.WAREHOUSE'},
            {key: 'price_type', label: 'PRODUCTS.PRICE_TYPE'},
            {key: 'salesperson', label: 'SALES.SALESPERSON'},
            {key: 'payment_terms', label: 'SALES.PAYMENT_TERMS'},
            {key: 'currency', label: 'SALES.CURRENCY'},
            {key: 'tax', label: 'TAX_RATES.TITLE'},
            {key: 'discount', label: 'SALES.DISCOUNT'}
          ]; track f.key) {
            <div class="field-toggle-item">
              <p-toggleSwitch [ngModel]="fieldVisibility()[f.key] !== false" [ngModelOptions]="{standalone: true}"
                (ngModelChange)="toggleField(f.key)" />
              <span>{{ f.label | translate }}</span>
            </div>
          }
        </div>
        <p-button icon="pi pi-check" size="small" [label]="'COMMON.SAVE' | translate"
          (onClick)="saveFieldVisibility()" />
      </div>
    }

    <!-- Line Items Section -->
    <div class="lines-section">
      <div class="lines-header">
        <div style="display: flex; align-items: center; gap: 0.5rem;">
          <h3>{{ 'SALES.LINE_ITEMS' | translate }}</h3>
          <p-button
            icon="pi pi-plus"
            [label]="'SALES.ADD_LINE' | translate"
            severity="contrast"
            [outlined]="true"
            size="small"
            (onClick)="addItem()"
            styleClass="header-add-btn"
          />
        </div>
        <div class="barcode-row-inline">
          <i class="pi pi-barcode barcode-icon"></i>
          <input pInputText #barcodeInput
            [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" style="color: rgba(255,255,255,0.6);"></i> }
        </div>
      </div>

      <table class="lines-table">
        <thead>
          <tr>
            <th class="col-num">#</th>
            <th class="col-product">{{ 'SALES.PRODUCT' | translate }}</th>
            @if (isFieldVisible('warehouse')) { <th class="col-warehouse">{{ 'SALES.WAREHOUSE' | translate }}</th> }
            <th class="col-unit">{{ 'SALES.UNIT' | translate }}</th>
            <th class="col-qty">{{ 'SALES.QUANTITY' | translate }}</th>
            <th class="col-price">{{ 'SALES.UNIT_PRICE' | translate }}</th>
            @if (isFieldVisible('discount')) { <th class="col-discount">{{ 'SALES.DISCOUNT' | translate }}</th> }
            @if (isFieldVisible('tax')) { <th class="col-tax">{{ 'SALES.TAX' | translate }}</th> }
            <th class="col-total">{{ 'SALES.LINE_TOTAL' | translate }}</th>
            <th class="col-action"></th>
          </tr>
        </thead>
        <tbody formArrayName="items">
          @for (item of items.controls; track item; let i = $index) {
            <tr [formGroupName]="i">
              <td class="row-num">{{ 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)"
                  (onChange)="onProductSelect(i, $event.value)"
                  appendTo="body"
                  [style]="{ width: '100%' }"
                  [placeholder]="'SALES.PRODUCT' | translate"
                  [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>
                @if (getProductBarcode(item.get('product_id')?.value); as bc) {
                  <div class="row-barcode"><i class="pi pi-barcode"></i> {{ bc }}</div>
                }
              </td>
              @if (isFieldVisible('warehouse')) {
                <td>
                  <p-select
                    formControlName="warehouse_id"
                    [options]="warehouses()"
                    optionLabel="name"
                    optionValue="id"
                    [showClear]="true"
                    [placeholder]="'SALES.WAREHOUSE' | translate"
                    [style]="{ width: '100%' }"
                    appendTo="body"
                  />
                  @if (getLineStock(i) !== null) {
                    <div class="stock-badge" [class.stock-zero]="getLineStock(i) === 0">
                      <i class="pi pi-box"></i> {{ getLineStock(i) | number:'1.0-2' }}
                    </div>
                  }
                </td>
              }
              <td>
                <p-select
                  formControlName="unit_id"
                  [options]="(units$ | async) || []"
                  optionLabel="name"
                  optionValue="id"
                  [placeholder]="'SALES.UNIT' | translate"
                  [style]="{ width: '100%' }"
                  appendTo="body"
                />
              </td>
              <td>
                <p-inputNumber formControlName="quantity" [min]="0.01" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-inputNumber formControlName="unit_price" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              @if (isFieldVisible('discount')) {
                <td>
                  <p-inputNumber formControlName="discount_percent" [min]="0" [max]="100" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="2" [style]="{ width: '100%' }" suffix="%" />
                </td>
              }
              @if (isFieldVisible('tax')) {
                <td>
                  <p-select
                    formControlName="tax_rate_id"
                    [options]="(taxRates$ | async) || []"
                    optionLabel="name"
                    optionValue="id"
                    [showClear]="true"
                    [placeholder]="'SALES.TAX' | translate"
                    [style]="{ width: '100%' }"
                    appendTo="body"
                  />
                </td>
              }
              <td class="amount line-total-cell">
                {{ getLineTotal(i) | number:'1.2-2' }}
              </td>
              <td>
                <p-button
                  icon="pi pi-times"
                  [rounded]="true"
                  [text]="true"
                  severity="danger"
                  (onClick)="removeItem(i)"
                  [disabled]="items.length <= 1"
                  size="small"
                />
              </td>
            </tr>
          }
        </tbody>
      </table>

      @if (items.length === 0) {
        <div class="no-items">{{ 'SALES.NO_ITEMS' | translate }}</div>
      }
    </div>

    <!-- Bottom: Totals + Notes side by side -->
    <div class="bottom-row">
      <div class="notes-compact">
        <div class="form-strip-field grow-2">
          <label>{{ 'SALES.NOTES' | translate }}</label>
          <textarea pTextarea formControlName="notes" rows="1" [autoResize]="true"></textarea>
        </div>
        <div class="form-strip-field grow-2">
          <label>{{ 'SALES.SUBJECT' | translate }}</label>
          <input pInputText formControlName="subject" />
        </div>
      </div>
      <div class="totals-section">
        <div class="totals-row">
          <span class="totals-label">{{ 'SALES.SUBTOTAL' | translate }}</span>
          <span class="totals-value">{{ rawSubtotal | number:'1.2-2' }}</span>
        </div>
        @if (lineDiscountTotal > 0) {
          <div class="totals-row">
            <span class="totals-label">{{ 'SALES.LINE_DISCOUNTS' | translate }}</span>
            <span class="totals-value discount">- {{ lineDiscountTotal | number:'1.2-2' }}</span>
          </div>
        }
        <!-- Overall invoice discount -->
        <div class="totals-row overall-discount-row">
          <span class="totals-label">{{ 'SALES.OVERALL_DISCOUNT' | translate }}</span>
          <div class="overall-discount-input">
            <p-inputNumber
              [ngModel]="overallDiscountValue()"
              (ngModelChange)="overallDiscountValue.set($event)"
              [ngModelOptions]="{standalone: true}"
              [min]="0"
              [max]="overallDiscountType() === 'percent' ? 100 : subtotal"
              mode="decimal"
              [minFractionDigits]="0"
              [maxFractionDigits]="2"
              [style]="{ width: '100px' }"
              inputStyleClass="discount-input-sm"
            />
            <p-button
              [label]="overallDiscountType() === 'percent' ? '%' : overallDiscountType() === 'amount' ? (invoiceForm.get('currency_code')?.value || 'KWD') : '%'"
              size="small"
              [outlined]="true"
              severity="secondary"
              (onClick)="overallDiscountType.set(overallDiscountType() === 'percent' ? 'amount' : 'percent')"
              [style]="{ 'min-width': '40px' }"
            />
          </div>
        </div>
        @if (overallDiscountComputed > 0) {
          <div class="totals-row">
            <span class="totals-label">{{ 'SALES.AFTER_DISCOUNT' | translate }}</span>
            <span class="totals-value">{{ subtotalAfterDiscount | number:'1.2-2' }}</span>
          </div>
        }
        <div class="totals-row grand-total">
          <span class="totals-label">{{ 'SALES.TOTAL' | translate }}</span>
          <span class="totals-value">{{ total | number:'1.2-2' }}</span>
        </div>
      </div>
    </div>

    <!-- Inline Payment Section -->
    <div class="inline-pay-section">
      <div class="inline-pay-toggle">
        <p-toggleSwitch [ngModel]="inlinePayEnabled()" (ngModelChange)="onInlinePayToggle($event)" [ngModelOptions]="{standalone: true}" />
        <span class="inline-pay-label">{{ 'SALES.RECORD_PAYMENT' | translate }}</span>
        @if (inlinePayEnabled()) {
          <div class="inline-pay-quick-btns">
            <p-button [label]="'SALES.PAY_FULL' | translate" size="small" severity="success" [outlined]="true"
              (onClick)="setInlinePayFull()" />
          </div>
        }
      </div>
      @if (inlinePayEnabled()) {
        <div class="inline-pay-fields">
          <div class="inline-pay-field">
            <label>{{ 'SALES.AMOUNT' | translate }}</label>
            <p-inputNumber [ngModel]="inlinePayAmount()" (ngModelChange)="inlinePayAmount.set($event)"
              [ngModelOptions]="{standalone: true}" [min]="0.01" [max]="total"
              mode="decimal" [minFractionDigits]="2" [style]="{ width: '100%' }" />
          </div>
          <div class="inline-pay-field grow">
            <label>{{ 'SALES.PAYMENT_DESTINATION' | translate }}</label>
            <p-select
              [ngModel]="inlinePayDestId()" (ngModelChange)="inlinePayDestId.set($event)"
              [ngModelOptions]="{standalone: true}"
              [options]="paymentDestinations()"
              optionValue="id"
              [style]="{ width: '100%' }"
              appendTo="body"
            >
              <ng-template #selectedItem let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 4px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
              <ng-template #item let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 4px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
            </p-select>
          </div>
          <div class="inline-pay-field">
            <label>{{ 'SALES.REFERENCE' | translate }}</label>
            <input pInputText [ngModel]="inlinePayReference()" (ngModelChange)="inlinePayReference.set($event)"
              [ngModelOptions]="{standalone: true}" />
          </div>
        </div>
        @if (getInlinePayDest()?.payment_method === 'check') {
          <div class="inline-pay-fields">
            <div class="inline-pay-field">
              <label>{{ 'SALES.CHECK_NUMBER' | translate }}</label>
              <input pInputText [ngModel]="inlinePayCheckNumber()" (ngModelChange)="inlinePayCheckNumber.set($event)"
                [ngModelOptions]="{standalone: true}" />
            </div>
            <div class="inline-pay-field">
              <label>{{ 'SALES.CHECK_DATE' | translate }}</label>
              <p-datepicker [ngModel]="inlinePayCheckDate()" (ngModelChange)="inlinePayCheckDate.set($event)"
                [ngModelOptions]="{standalone: true}" dateFormat="yy-mm-dd" [showIcon]="true" [style]="{ width: '100%' }" />
            </div>
            <div class="inline-pay-field">
              <label>{{ 'SALES.CHECK_BANK' | translate }}</label>
              <input pInputText [ngModel]="inlinePayCheckBank()" (ngModelChange)="inlinePayCheckBank.set($event)"
                [ngModelOptions]="{standalone: true}" />
            </div>
          </div>
        }
      }
    </div>
  </form>
  <div class="dialog-custom-footer">
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="dialogVisible.set(false)"
    />
    <p-button
      [label]="inlinePayEnabled() ? ('SALES.SAVE_AND_PAY' | translate) : ('COMMON.SAVE' | translate)"
      [icon]="inlinePayEnabled() ? 'pi pi-dollar' : 'pi pi-check'"
      [severity]="inlinePayEnabled() ? 'success' : 'primary'"
      (onClick)="onSave()"
      [loading]="saving()"
      [disabled]="items.length < 1"
    />
    <p-button
      [label]="'SALES.SAVE_AND_PRINT' | translate"
      icon="pi pi-print"
      severity="help"
      (onClick)="onSaveAndPrint()"
      [loading]="saving()"
      [disabled]="items.length < 1"
    />
  </div>
</app-form-dialog>

<!-- View/Detail Dialog -->
<p-dialog
  [header]="'SALES.INVOICE' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '1000px', maxHeight: '90vh' }"
  [closable]="true"
>
  @if (viewingInvoice(); as inv) {
    <div class="view-invoice">
      <!-- Header Info -->
      <div class="view-header-info">
        <div class="info-item">
          <label>{{ 'SALES.INVOICE_NUMBER' | translate }}</label>
          <span class="mono">{{ inv.invoice_number }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.DATE' | translate }}</label>
          <span>{{ inv.date }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.DUE_DATE' | translate }}</label>
          <span [class.text-danger]="isOverdue(inv)">
            {{ inv.due_date }}
            @if (isOverdue(inv)) {
              <i class="pi pi-exclamation-circle"></i>
            }
          </span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.STATUS' | translate }}</label>
          <p-tag
            [value]="getStatusLabel(inv.status)"
            [severity]="getStatusSeverity(inv.status)"
          />
        </div>
        <div class="info-item">
          <label>{{ 'SALES.PAYMENT_STATUS' | translate }}</label>
          <p-tag
            [value]="getStatusLabel(inv.payment_status)"
            [severity]="getStatusSeverity(inv.payment_status)"
            [rounded]="true"
          />
        </div>
        <div class="info-item">
          <label>{{ 'SALES.CUSTOMER' | translate }}</label>
          <span>{{ inv.customer_name }}</span>
        </div>
        @if (inv.salesperson_name) {
          <div class="info-item">
            <label>{{ 'SALES.SALESPERSON' | translate }}</label>
            <span>{{ inv.salesperson_name }}</span>
          </div>
        }
        @if (inv.order_number) {
          <div class="info-item">
            <label>{{ 'SALES.ORDER_NUMBER' | translate }}</label>
            <span class="mono">{{ inv.order_number }}</span>
          </div>
        }
        <div class="info-item">
          <label>{{ 'SALES.CURRENCY' | translate }}</label>
          <span>{{ inv.currency_code }}</span>
        </div>
      </div>

      <!-- Summary Cards -->
      <div class="summary-cards">
        <div class="summary-card">
          <span class="card-label">{{ 'SALES.TOTAL' | translate }}</span>
          <span class="card-value">{{ inv.total | number:'1.2-2' }}</span>
        </div>
        <div class="summary-card paid">
          <span class="card-label">{{ 'SALES.AMOUNT_PAID' | translate }}</span>
          <span class="card-value">{{ inv.amount_paid | number:'1.2-2' }}</span>
        </div>
        <div class="summary-card" [class.overdue-card]="isOverdue(inv)">
          <span class="card-label">{{ 'SALES.BALANCE_DUE' | translate }}</span>
          <span class="card-value">{{ inv.balance_due | number:'1.2-2' }}</span>
        </div>
        <div class="summary-card" [class.overdue-card]="isOverdue(inv)">
          <span class="card-label">
            @if (isOverdue(inv)) {
              {{ 'SALES.DAYS_OVERDUE' | translate }}
            } @else {
              {{ 'SALES.DAYS_UNTIL_DUE' | translate }}
            }
          </span>
          <span class="card-value">{{ getDaysInfo(inv).days }}</span>
        </div>
      </div>

      <!-- Action buttons -->
      <div class="post-action-bar">
        @if (inv.status === 'approved' || (inv.status === 'draft' && approvalWorkflow() === 'none')) {
          <p-button
            [label]="'SALES.POST' | translate"
            icon="pi pi-check-circle"
            severity="success"
            size="large"
            (onClick)="postInvoice(inv)"
          />
        }
        <p-button
          [label]="'SALES.PRINT_INVOICE' | translate"
          icon="pi pi-print"
          severity="info"
          (onClick)="printInvoice(inv)"
        />
      </div>
      @if (inv.status === 'posted' || inv.status === 'partially_paid') {
        <div class="post-action-bar">
          <p-button
            [label]="'SALES.RECORD_PAYMENT' | translate"
            icon="pi pi-dollar"
            severity="success"
            (onClick)="openPaymentDialog(inv)"
          />
        </div>
      }

      <!-- Tabs -->
      <p-tabs value="0">
        <p-tablist>
          <p-tab value="0">{{ 'SALES.LINE_ITEMS' | translate }}</p-tab>
          <p-tab value="1">{{ 'SALES.PAYMENTS' | translate }} ({{ invoicePayments().length }})</p-tab>
          @if (paymentSchedule().length > 0) {
            <p-tab value="2">{{ 'SALES.PAYMENT_SCHEDULE' | translate }}</p-tab>
          }
          @if (inv.journal_entry_id || inv.cogs_journal_entry_id) {
            <p-tab value="3">{{ 'SALES.JOURNAL_ENTRIES' | translate }}</p-tab>
          }
        </p-tablist>
        <p-tabpanels>
          <!-- Items Tab -->
          <p-tabpanel value="0">
            <table class="view-lines-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>{{ 'SALES.PRODUCT' | translate }}</th>
                  <th>{{ 'SALES.UNIT' | translate }}</th>
                  @if (inv.items && inv.items[0]?.warehouse_name) {
                    <th>{{ 'SALES.WAREHOUSE' | translate }}</th>
                  }
                  <th>{{ 'SALES.QUANTITY' | translate }}</th>
                  <th>{{ 'SALES.UNIT_PRICE' | translate }}</th>
                  <th>{{ 'SALES.DISCOUNT' | translate }}</th>
                  <th>{{ 'SALES.TAX' | translate }}</th>
                  <th>{{ 'SALES.LINE_TOTAL' | translate }}</th>
                </tr>
              </thead>
              <tbody>
                @for (item of inv.items; track $index) {
                  <tr>
                    <td>{{ $index + 1 }}</td>
                    <td>{{ item.product_name }}</td>
                    <td>{{ item.unit_name }}</td>
                    @if (inv.items && inv.items[0]?.warehouse_name) {
                      <td>{{ item.warehouse_name || '-' }}</td>
                    }
                    <td class="amount">{{ item.quantity }}</td>
                    <td class="amount">{{ item.unit_price | number:'1.2-2' }}</td>
                    <td class="amount">{{ item.discount_percent }}%</td>
                    <td>{{ item.tax_rate_name || '-' }}</td>
                    <td class="amount">{{ item.line_total | number:'1.2-2' }}</td>
                  </tr>
                }
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="6"></td>
                  <td><strong>{{ 'SALES.SUBTOTAL' | translate }}</strong></td>
                  <td class="amount"><strong>{{ inv.subtotal | number:'1.2-2' }}</strong></td>
                </tr>
                @if (+inv.discount_amount > 0) {
                  <tr>
                    <td colspan="6"></td>
                    <td>{{ 'SALES.DISCOUNT_AMOUNT' | translate }}</td>
                    <td class="amount discount">- {{ inv.discount_amount | number:'1.2-2' }}</td>
                  </tr>
                }
                @if (+inv.tax_amount > 0) {
                  <tr>
                    <td colspan="6"></td>
                    <td>{{ 'SALES.TAX_AMOUNT' | translate }}</td>
                    <td class="amount">{{ inv.tax_amount | number:'1.2-2' }}</td>
                  </tr>
                }
                <tr class="grand-total-row">
                  <td colspan="6"></td>
                  <td><strong>{{ 'SALES.TOTAL' | translate }}</strong></td>
                  <td class="amount"><strong>{{ inv.total | number:'1.2-2' }}</strong></td>
                </tr>
              </tfoot>
            </table>
          </p-tabpanel>

          <!-- Payments Tab -->
          <p-tabpanel value="1">
            @if (loadingPayments()) {
              <div class="loading-spinner">
                <i class="pi pi-spin pi-spinner" style="font-size: 2rem;"></i>
              </div>
            } @else if (invoicePayments().length === 0) {
              <div class="empty-tab">{{ 'SALES.NO_PAYMENTS' | translate }}</div>
            } @else {
              <table class="view-lines-table">
                <thead>
                  <tr>
                    <th>{{ 'SALES.PAYMENT_NUMBER' | translate }}</th>
                    <th>{{ 'SALES.DATE' | translate }}</th>
                    <th>{{ 'SALES.AMOUNT' | translate }}</th>
                    <th>{{ 'SALES.PAYMENT_METHOD' | translate }}</th>
                    <th>{{ 'SALES.STATUS' | translate }}</th>
                    <th>{{ 'SALES.REFERENCE' | translate }}</th>
                  </tr>
                </thead>
                <tbody>
                  @for (pay of invoicePayments(); track pay.id) {
                    <tr>
                      <td class="mono">{{ pay.payment_number }}</td>
                      <td>{{ pay.date }}</td>
                      <td class="amount">{{ pay.amount | number:'1.2-2' }}</td>
                      <td>{{ getPaymentMethodLabel(pay.payment_method) }}</td>
                      <td>
                        <p-tag
                          [value]="getStatusLabel(pay.status)"
                          [severity]="getStatusSeverity(pay.status)"
                        />
                      </td>
                      <td>{{ pay.reference || '-' }}</td>
                    </tr>
                  }
                </tbody>
              </table>
            }
          </p-tabpanel>

          <!-- Payment Schedule Tab -->
          @if (paymentSchedule().length > 0) {
            <p-tabpanel value="2">
              <table class="view-lines-table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>{{ 'SALES.DUE_DATE' | translate }}</th>
                    <th>{{ 'SALES.AMOUNT' | translate }}</th>
                    <th>{{ 'SALES.AMOUNT_PAID' | translate }}</th>
                    <th>{{ 'SALES.STATUS' | translate }}</th>
                  </tr>
                </thead>
                <tbody>
                  @for (sched of paymentSchedule(); track $index) {
                    <tr>
                      <td>{{ $index + 1 }}</td>
                      <td>{{ sched.due_date }}</td>
                      <td class="amount">{{ sched.amount | number:'1.2-2' }}</td>
                      <td class="amount">{{ sched.amount_paid | number:'1.2-2' }}</td>
                      <td>
                        <p-tag
                          [value]="getStatusLabel(sched.status || 'pending')"
                          [severity]="getStatusSeverity(sched.status || 'pending')"
                        />
                      </td>
                    </tr>
                  }
                </tbody>
              </table>
            </p-tabpanel>
          }

          <!-- Journal Entries Tab -->
          @if (inv.journal_entry_id || inv.cogs_journal_entry_id) {
            <p-tabpanel value="3">
              @if (jeLoading()) {
                <div class="loading-spinner"><i class="pi pi-spin pi-spinner" style="font-size: 2rem;"></i></div>
              } @else {
                <div class="je-section">
                  @if (revenueJe(); as je) {
                    <div class="je-block">
                      <div class="je-block-header">
                        <i class="pi pi-book"></i>
                        <span class="je-block-title">{{ 'SALES.REVENUE_JE' | translate }}</span>
                        <span class="je-number">{{ je.entry_number }}</span>
                        <p-tag [value]="je.status" [severity]="je.status === 'posted' ? 'success' : 'warn'" />
                      </div>
                      @if (je.lines?.length) {
                        <table class="je-lines-table">
                          <thead>
                            <tr>
                              <th>{{ 'SALES.JE_ACCOUNT' | translate }}</th>
                              <th class="text-end">{{ 'SALES.JE_DEBIT' | translate }}</th>
                              <th class="text-end">{{ 'SALES.JE_CREDIT' | translate }}</th>
                            </tr>
                          </thead>
                          <tbody>
                            @for (line of je.lines; track line.id) {
                              <tr>
                                <td>{{ line.account?.name || line.account?.code || '—' }}</td>
                                <td class="text-end">{{ line.debit | number:'1.2-2' }}</td>
                                <td class="text-end">{{ line.credit | number:'1.2-2' }}</td>
                              </tr>
                            }
                          </tbody>
                        </table>
                      }
                    </div>
                  }
                  @if (cogsJe(); as je) {
                    <div class="je-block">
                      <div class="je-block-header">
                        <i class="pi pi-calculator"></i>
                        <span class="je-block-title">{{ 'SALES.COGS_JE' | translate }}</span>
                        <span class="je-number">{{ je.entry_number }}</span>
                        <p-tag [value]="je.status" [severity]="je.status === 'posted' ? 'success' : 'warn'" />
                      </div>
                      @if (je.lines?.length) {
                        <table class="je-lines-table">
                          <thead>
                            <tr>
                              <th>{{ 'SALES.JE_ACCOUNT' | translate }}</th>
                              <th class="text-end">{{ 'SALES.JE_DEBIT' | translate }}</th>
                              <th class="text-end">{{ 'SALES.JE_CREDIT' | translate }}</th>
                            </tr>
                          </thead>
                          <tbody>
                            @for (line of je.lines; track line.id) {
                              <tr>
                                <td>{{ line.account?.name || line.account?.code || '—' }}</td>
                                <td class="text-end">{{ line.debit | number:'1.2-2' }}</td>
                                <td class="text-end">{{ line.credit | number:'1.2-2' }}</td>
                              </tr>
                            }
                          </tbody>
                        </table>
                      }
                    </div>
                  }
                  @if (inv.posted_at) {
                    <div class="je-meta">
                      {{ 'SALES.POSTED_BY' | translate }}: {{ inv.posted_by_name }}
                      {{ 'SALES.POSTED_AT' | translate }}: {{ inv.posted_at | date:'short' }}
                    </div>
                  }
                </div>
              }
            </p-tabpanel>
          }
        </p-tabpanels>
      </p-tabs>

      <!-- Cancellation info -->
      @if (inv.status === 'cancelled') {
        <div class="cancellation-banner">
          <i class="pi pi-ban"></i>
          <div class="cancel-info">
            <span class="cancel-title">{{ 'SALES.CANCELLED' | translate }}</span>
            @if (inv.cancelled_at) {
              <span class="cancel-meta">{{ inv.cancelled_at | date:'medium' }}</span>
            }
            @if (inv.cancellation_reason) {
              <span class="cancel-reason">{{ inv.cancellation_reason }}</span>
            }
          </div>
        </div>
      }

      <!-- Notes -->
      @if (inv.notes || inv.notes_ar) {
        <div class="view-description">
          @if (inv.notes) {
            <label>{{ 'SALES.NOTES' | translate }}</label>
            <p>{{ inv.notes }}</p>
          }
          @if (inv.notes_ar) {
            <label>{{ 'SALES.NOTES_AR' | translate }}</label>
            <p>{{ inv.notes_ar }}</p>
          }
        </div>
      }
    </div>
  }
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CLOSE' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="viewDialogVisible.set(false)"
    />
  </ng-template>
</p-dialog>

<!-- Record Payment Dialog -->
<p-dialog
  [header]="'SALES.RECORD_PAYMENT' | translate"
  [(visible)]="paymentDialogVisible"
  [modal]="true"
  [style]="{ width: '550px' }"
  [closable]="true"
>
  @if (paymentInvoice(); as inv) {
    <div class="payment-dialog">
      <div class="payment-summary">
        <div class="pay-info-row">
          <span>{{ 'SALES.INVOICE' | translate }}:</span>
          <span class="mono">{{ inv.invoice_number }}</span>
        </div>
        <div class="pay-info-row">
          <span>{{ 'SALES.TOTAL' | translate }}:</span>
          <span class="amount">{{ inv.total | number:'1.2-2' }}</span>
        </div>
        <div class="pay-info-row">
          <span>{{ 'SALES.BALANCE_DUE' | translate }}:</span>
          <span class="amount highlight">{{ inv.balance_due | number:'1.2-2' }}</span>
        </div>
      </div>
      <form [formGroup]="paymentForm" class="payment-form">
        <div class="pay-grid">
          <div class="pay-field">
            <label>{{ 'SALES.DATE' | translate }} *</label>
            <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" [style]="{ width: '100%' }" />
          </div>
          <div class="pay-field">
            <label>{{ 'SALES.AMOUNT' | translate }} *</label>
            <p-inputNumber formControlName="amount" [min]="0.01" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
          </div>
        </div>
        <div class="pay-grid">
          <div class="pay-field full">
            <label>{{ 'SALES.PAYMENT_DESTINATION' | translate }} *</label>
            <p-select
              [options]="paymentDestinations()"
              optionValue="id"
              [ngModel]="getSelectedDestinationId()"
              (ngModelChange)="onDestinationChange($event)"
              [ngModelOptions]="{standalone: true}"
              [style]="{ width: '100%' }"
              appendTo="body"
            >
              <ng-template #selectedItem let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 6px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
              <ng-template #item let-dest>
                <span><i [class]="dest.icon" style="margin-inline-end: 6px;"></i>{{ dest.label }} <small style="color: #94a3b8;">({{ dest.sublabel }})</small></span>
              </ng-template>
            </p-select>
          </div>
        </div>
        @if (paymentForm.get('payment_method')?.value === 'check') {
          <div class="pay-grid">
            <div class="pay-field">
              <label>{{ 'SALES.CHECK_NUMBER' | translate }}</label>
              <input pInputText formControlName="check_number" />
            </div>
            <div class="pay-field">
              <label>{{ 'SALES.CHECK_DATE' | translate }}</label>
              <p-datepicker formControlName="check_date" dateFormat="yy-mm-dd" [showIcon]="true" [style]="{ width: '100%' }" />
            </div>
          </div>
          <div class="pay-grid">
            <div class="pay-field full">
              <label>{{ 'SALES.CHECK_BANK' | translate }}</label>
              <input pInputText formControlName="check_bank" />
            </div>
          </div>
        }
        <div class="pay-grid">
          <div class="pay-field full">
            <label>{{ 'SALES.REFERENCE' | translate }}</label>
            <input pInputText formControlName="reference" />
          </div>
        </div>
        <div class="pay-grid">
          <div class="pay-field full">
            <label>{{ 'SALES.NOTES' | translate }}</label>
            <textarea pTextarea formControlName="notes" rows="2"></textarea>
          </div>
        </div>
      </form>
    </div>
  }
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="paymentDialogVisible.set(false)"
    />
    <p-button
      [label]="'SALES.RECORD_PAYMENT' | translate"
      icon="pi pi-check"
      (onClick)="onSavePayment()"
      [loading]="savingPayment()"
    />
  </ng-template>
</p-dialog>

<!-- Quick Add Customer Dialog -->
<p-dialog
  [header]="'SALES.ADD_CUSTOMER' | translate"
  [(visible)]="quickAddVisible"
  [modal]="true"
  [style]="{ width: '420px' }"
  [closable]="true"
>
  <form [formGroup]="quickAddForm" class="quick-add-form" style="display: flex; flex-direction: column; gap: 1rem;">
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.NAME_AR' | translate }} *</label>
      <input pInputText formControlName="name_ar" style="width: 100%" />
    </div>
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.NAME_EN' | translate }}</label>
      <input pInputText formControlName="name_en" style="width: 100%" />
    </div>
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.PHONE' | translate }}</label>
      <input pInputText formControlName="phone" style="width: 100%" />
    </div>
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.EMAIL' | translate }}</label>
      <input pInputText formControlName="email" style="width: 100%" type="email" />
    </div>
  </form>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="quickAddVisible.set(false)"
    />
    <p-button
      [label]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="saveQuickCustomer()"
      [loading]="quickAddSaving()"
    />
  </ng-template>
</p-dialog>
