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

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

  <ng-template #bodyTpl let-o>
    <tr>
      <td class="mono">{{ o.order_number }}</td>
      <td>{{ o.date }}</td>
      <td>{{ o.expected_delivery_date || '-' }}</td>
      <td>{{ o.customer_name }}</td>
      <td>{{ o.salesperson_name || '-' }}</td>
      <td class="amount">{{ o.total | number:'1.2-2' }}</td>
      <td>
        <p-tag
          [value]="getStatusLabel(o.status)"
          [severity]="getStatusSeverity(o.status)"
        />
      </td>
      <td>
        @if (o.delivery_status) {
          <p-tag
            [value]="getStatusLabel(o.delivery_status)"
            [severity]="getStatusSeverity(o.delivery_status)"
            [rounded]="true"
          />
        } @else {
          <span>-</span>
        }
      </td>
      <td>
        @if (o.invoice_status) {
          <p-tag
            [value]="getStatusLabel(o.invoice_status)"
            [severity]="getStatusSeverity(o.invoice_status)"
            [rounded]="true"
          />
        } @else {
          <span>-</span>
        }
      </td>
      <td>
        <div class="action-buttons">
          <p-button
            icon="pi pi-eye"
            [rounded]="true"
            [text]="true"
            severity="info"
            (onClick)="viewOrder(o)"
            [pTooltip]="'COMMON.VIEW' | translate"
          />
          <p-button
            icon="pi pi-print"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="printOrder(o)"
            [pTooltip]="'SALES.PRINT' | translate"
          />
          @if (o.status === 'draft') {
            <p-button
              icon="pi pi-pencil"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="editOrder(o)"
              [pTooltip]="'COMMON.EDIT' | translate"
            />
            <p-button
              icon="pi pi-check-circle"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="confirmOrder(o)"
              [pTooltip]="'SALES.CONFIRM' | translate"
            />
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="deleteOrder(o)"
              [pTooltip]="'COMMON.DELETE' | translate"
            />
          }
          @if (o.status === 'confirmed' || o.status === 'partially_delivered') {
            <p-button
              icon="pi pi-truck"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="createDelivery(o)"
              [pTooltip]="'SALES.CREATE_DELIVERY' | translate"
            />
          }
          @if (o.status === 'confirmed' || o.status === 'delivered' || o.status === 'partially_delivered' || o.status === 'partially_invoiced') {
            <p-button
              icon="pi pi-file"
              [rounded]="true"
              [text]="true"
              severity="warn"
              (onClick)="createInvoice(o)"
              [pTooltip]="'SALES.CREATE_INVOICE' | translate"
            />
          }
          @if (o.status !== 'draft' && o.status !== 'cancelled' && o.status !== 'closed') {
            <p-button
              icon="pi pi-lock"
              [rounded]="true"
              [text]="true"
              severity="secondary"
              (onClick)="closeOrder(o)"
              [pTooltip]="'SALES.CLOSED' | translate"
            />
          }
          <p-button
            icon="pi pi-copy"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="duplicateOrder(o)"
            [pTooltip]="'SALES.DUPLICATE' | translate"
          />
          @if (o.status !== 'cancelled' && o.status !== 'closed') {
            <p-button
              icon="pi pi-ban"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="cancelOrder(o)"
              [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]="editingOrder() ? ('SALES.EDIT_ORDER' | translate) : ('SALES.NEW_ORDER' | translate)"
  width="950px"
  [saving]="saving()"
  [showFooter]="false"
>
  <form [formGroup]="orderForm" class="order-form">
    <!-- Row 1: Customer + Date + Expected Delivery -->
    <div class="form-grid">
      <div class="form-field span-2">
        <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" /></label>
        <p-select
          formControlName="customer_id"
          [options]="searchedCustomers()"
          optionValue="id"
          [filter]="true"
          [filterBy]="'name,name_ar,name_en,code'"
          (onFilter)="onCustomerSearch($event)"
          [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-field">
        <label>{{ 'SALES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-field">
        <label>{{ 'SALES.EXPECTED_DELIVERY' | translate }}</label>
        <p-datepicker formControlName="expected_delivery_date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
    </div>

    <!-- Row 2: Currency + Exchange Rate + Salesperson + Payment Terms -->
    <div class="form-grid">
      <div class="form-field">
        <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-field">
        <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-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>
      <div class="form-field">
        <label>{{ 'SALES.PAYMENT_TERMS' | translate }}</label>
        <p-inputNumber formControlName="payment_terms_days" [min]="0" [style]="{ width: '100%' }" />
      </div>
    </div>

    <!-- Row 3: Reference + Subject -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'SALES.REFERENCE' | translate }}</label>
        <input pInputText formControlName="reference" />
      </div>
      <div class="form-field span-2">
        <label>{{ 'SALES.SUBJECT' | translate }}</label>
        <input pInputText formControlName="subject" />
      </div>
    </div>

    <!-- Line Items Section -->
    <div class="lines-section">
      <div class="lines-header">
        <h3>{{ 'SALES.LINE_ITEMS' | translate }}</h3>
        <p-button
          icon="pi pi-plus"
          [label]="'SALES.ADD_LINE' | translate"
          severity="contrast"
          styleClass="header-add-btn"
          size="small"
          (onClick)="addItem()"
        />
      </div>

      <div class="barcode-row">
        <span class="pi pi-barcode barcode-icon"></span>
        <input 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>

      <table class="lines-table">
        <thead>
          <tr>
            <th class="col-product">{{ 'SALES.PRODUCT' | 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>
            <th class="col-discount">{{ 'SALES.DISCOUNT' | translate }}</th>
            <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>
                <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: '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>
              <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>
              <td>
                <p-inputNumber formControlName="discount_percent" [min]="0" [max]="100" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="2" [style]="{ width: '100%' }" suffix="%" />
              </td>
              <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>

    <!-- Totals Section -->
    <div class="totals-section">
      <div class="totals-row">
        <span class="totals-label">{{ 'SALES.SUBTOTAL' | translate }}</span>
        <span class="totals-value">{{ subtotal | number:'1.2-2' }}</span>
      </div>
      <div class="totals-row">
        <span class="totals-label">{{ 'SALES.DISCOUNT_AMOUNT' | translate }}</span>
        <span class="totals-value discount">- {{ discountAmount | 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>

    <!-- Notes -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'SALES.NOTES' | translate }}</label>
        <textarea pTextarea formControlName="notes" rows="2"></textarea>
      </div>
      <div class="form-field span-2">
        <label>{{ 'SALES.NOTES_AR' | translate }}</label>
        <textarea pTextarea formControlName="notes_ar" rows="2"></textarea>
      </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]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="onSave()"
      [loading]="saving()"
      [disabled]="items.length < 1"
    />
  </div>
</app-form-dialog>

<!-- View Dialog -->
<p-dialog
  [header]="'SALES.ORDER' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '900px' }"
  [closable]="true"
>
  @if (viewingOrder(); as o) {
    <div class="view-order">
      <div class="view-header-info">
        <div class="info-item">
          <label>{{ 'SALES.ORDER_NUMBER' | translate }}</label>
          <span class="mono">{{ o.order_number }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.DATE' | translate }}</label>
          <span>{{ o.date }}</span>
        </div>
        @if (o.expected_delivery_date) {
          <div class="info-item">
            <label>{{ 'SALES.EXPECTED_DELIVERY' | translate }}</label>
            <span>{{ o.expected_delivery_date }}</span>
          </div>
        }
        <div class="info-item">
          <label>{{ 'SALES.STATUS' | translate }}</label>
          <p-tag
            [value]="getStatusLabel(o.status)"
            [severity]="getStatusSeverity(o.status)"
          />
        </div>
        @if (o.delivery_status) {
          <div class="info-item">
            <label>{{ 'SALES.DELIVERY_STATUS' | translate }}</label>
            <p-tag
              [value]="getStatusLabel(o.delivery_status)"
              [severity]="getStatusSeverity(o.delivery_status)"
              [rounded]="true"
            />
          </div>
        }
        @if (o.invoice_status) {
          <div class="info-item">
            <label>{{ 'SALES.INVOICE_STATUS' | translate }}</label>
            <p-tag
              [value]="getStatusLabel(o.invoice_status)"
              [severity]="getStatusSeverity(o.invoice_status)"
              [rounded]="true"
            />
          </div>
        }
        <div class="info-item">
          <label>{{ 'SALES.CUSTOMER' | translate }}</label>
          <span>{{ o.customer_name }}</span>
        </div>
        @if (o.salesperson_name) {
          <div class="info-item">
            <label>{{ 'SALES.SALESPERSON' | translate }}</label>
            <span>{{ o.salesperson_name }}</span>
          </div>
        }
        @if (o.reference) {
          <div class="info-item">
            <label>{{ 'SALES.REFERENCE' | translate }}</label>
            <span>{{ o.reference }}</span>
          </div>
        }
        @if (o.quotation_number) {
          <div class="info-item">
            <label>{{ 'SALES.QUOTATION_NUMBER' | translate }}</label>
            <span class="mono">{{ o.quotation_number }}</span>
          </div>
        }
        <div class="info-item">
          <label>{{ 'SALES.CURRENCY' | translate }}</label>
          <span>{{ o.currency_code }}</span>
        </div>
      </div>

      @if (o.notes || o.notes_ar) {
        <div class="view-description">
          @if (o.notes) {
            <label>{{ 'SALES.NOTES' | translate }}</label>
            <p>{{ o.notes }}</p>
          }
          @if (o.notes_ar) {
            <label>{{ 'SALES.NOTES_AR' | translate }}</label>
            <p>{{ o.notes_ar }}</p>
          }
        </div>
      }

      <table class="view-lines-table">
        <thead>
          <tr>
            <th>#</th>
            <th>{{ 'SALES.PRODUCT' | translate }}</th>
            <th>{{ 'SALES.UNIT' | 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 o.items; track $index) {
            <tr>
              <td>{{ $index + 1 }}</td>
              <td>{{ item.product_name }}</td>
              <td>{{ item.unit_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>{{ o.subtotal | number:'1.2-2' }}</strong></td>
          </tr>
          @if (+o.discount_amount > 0) {
            <tr>
              <td colspan="6"></td>
              <td>{{ 'SALES.DISCOUNT_AMOUNT' | translate }}</td>
              <td class="amount discount">- {{ o.discount_amount | number:'1.2-2' }}</td>
            </tr>
          }
          @if (+o.tax_amount > 0) {
            <tr>
              <td colspan="6"></td>
              <td>{{ 'SALES.TAX_AMOUNT' | translate }}</td>
              <td class="amount">{{ o.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>{{ o.total | number:'1.2-2' }}</strong></td>
          </tr>
        </tfoot>
      </table>
    </div>
  }
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CLOSE' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="viewDialogVisible.set(false)"
    />
  </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>
