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

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

  <ng-template #bodyTpl let-r>
    <tr>
      <td class="mono">{{ r.return_number }}</td>
      <td>{{ r.date }}</td>
      <td class="mono">{{ r.bill_number || '-' }}</td>
      <td>{{ r.supplier_name }}</td>
      <td class="amount">{{ r.total | number:'1.2-2' }}</td>
      <td><p-tag [value]="getStatusLabel(r.status)" [severity]="getStatusSeverity(r.status)" /></td>
      <td>
        <div class="action-buttons">
          <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="info" (onClick)="viewReturn(r)" [pTooltip]="'COMMON.VIEW' | translate" />
          <p-button icon="pi pi-print" [rounded]="true" [text]="true" severity="secondary" (onClick)="printReturn(r)" [pTooltip]="'PURCHASES.PRINT' | translate" />
          @if (r.status === 'draft' || r.status === 'pending_approval' || r.status === 'approved') {
            <p-button icon="pi pi-bolt" [rounded]="true" [text]="true" severity="success" (onClick)="quickProcess(r)" [pTooltip]="'PURCHASES.QUICK_PROCESS' | translate" />
          }
          @if (r.status === 'draft') {
            <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" (onClick)="editReturn(r)" [pTooltip]="'COMMON.EDIT' | translate" />
            <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="deleteReturn(r)" [pTooltip]="'COMMON.DELETE' | translate" />
          }
          @if (r.status !== 'cancelled' && r.status !== 'posted') {
            <p-button icon="pi pi-ban" [rounded]="true" [text]="true" severity="danger" (onClick)="cancelReturn(r)" [pTooltip]="'PURCHASES.CANCEL' | translate" />
          }
        </div>
      </td>
    </tr>
  </ng-template>

  <ng-template #filtersTpl>
    <app-sales-filter-bar [statusOptions]="statusOptions" [customers]="filterSuppliers()" (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" />
</div>

<!-- Create/Edit Return Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingReturn() ? ('PURCHASES.EDIT_RETURN' | translate) : ('PURCHASES.NEW_RETURN' | translate)"
  width="80vw"
  [saving]="saving()"
  [showFooter]="false"
>
  <form [formGroup]="returnForm" class="return-form">
    <!-- Standalone toggle -->
    <div style="margin-bottom: 0.5rem">
      <div class="standalone-toggle">
        <p-button
          [label]="(standaloneMode() ? 'PURCHASES.BILL_RETURN' : 'PURCHASES.STANDALONE_RETURN') | translate"
          [icon]="standaloneMode() ? 'pi pi-file' : 'pi pi-undo'"
          severity="secondary"
          [outlined]="true"
          size="small"
          (onClick)="toggleStandaloneMode()"
        />
        @if (standaloneMode()) {
          <span class="standalone-hint">{{ 'PURCHASES.STANDALONE_HINT' | translate }}</span>
        }
      </div>
    </div>

    <!-- Primary form strip -->
    <div class="form-strip">
      @if (!standaloneMode()) {
        <!-- Bill mode: bill selector -->
        <div class="form-strip-field grow-2">
          <label>{{ 'PURCHASES.BILL' | translate }} *</label>
          <p-select
            formControlName="bill_id"
            [options]="bills()"
            optionLabel="bill_number"
            optionValue="id"
            [filter]="true"
            filterBy="bill_number,supplier_name"
            [placeholder]="'PURCHASES.SELECT_BILL' | translate"
            [style]="{ width: '100%' }"
            appendTo="body"
            (onChange)="onBillSelect($event.value)"
          >
            <ng-template #item let-b>
              <span>{{ b.bill_number }} — {{ b.supplier_name }} ({{ b.total | number:'1.2-2' }})</span>
            </ng-template>
            <ng-template #selectedItem let-b>
              <span>{{ b.bill_number }} — {{ b.supplier_name }}</span>
            </ng-template>
          </p-select>
        </div>
      } @else {
        <!-- Standalone mode: supplier selector -->
        <div class="form-strip-field grow-2">
          <label>{{ 'PURCHASES.SUPPLIER' | translate }} *</label>
          <p-select
            formControlName="supplier_id"
            [options]="suppliers()"
            optionLabel="name"
            optionValue="id"
            [filter]="true"
            filterBy="name,code"
            [placeholder]="'PURCHASES.SELECT_SUPPLIER' | translate"
            [style]="{ width: '100%' }"
            appendTo="body"
          />
        </div>
      }
      <div class="form-strip-field">
        <label>{{ 'PURCHASES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
    </div>

    <!-- Secondary strip: Reason fields -->
    <div class="form-strip secondary">
      <div class="form-strip-field grow-2">
        <label>{{ 'PURCHASES.REASON' | translate }} *</label>
        <input pInputText formControlName="reason" />
      </div>
      <div class="form-strip-field grow-2">
        <label>{{ 'PURCHASES.REASON_AR' | translate }}</label>
        <input pInputText formControlName="reason_ar" />
      </div>
    </div>

    <!-- Standalone Items -->
    @if (standaloneMode()) {
      <div class="lines-section">
        <div class="lines-header">
          <div style="display: flex; align-items: center; gap: 0.5rem;">
            <h3>{{ 'PURCHASES.RETURN_ITEMS' | translate }}</h3>
            <p-button
              icon="pi pi-plus"
              [label]="'PURCHASES.ADD_ITEM' | translate"
              severity="contrast"
              [outlined]="true"
              size="small"
              (onClick)="addStandaloneItem()"
              styleClass="header-add-btn"
            />
          </div>
          <p-button
            icon="pi pi-cog"
            [rounded]="true"
            [text]="true"
            severity="contrast"
            (onClick)="fieldSettingsVisible.set(!fieldSettingsVisible())"
            [pTooltip]="'PURCHASES.FIELD_SETTINGS' | translate"
            styleClass="header-add-btn"
          />
        </div>
        @if (fieldSettingsVisible()) {
          <div class="field-settings-panel">
            <div class="field-settings-grid">
              <div class="field-toggle-item">
                <input type="checkbox" [checked]="isFieldVisible('warehouse')" (change)="toggleField('warehouse')" />
                <span>{{ 'PURCHASES.WAREHOUSE' | translate }}</span>
              </div>
              <div class="field-toggle-item">
                <input type="checkbox" [checked]="isFieldVisible('discount')" (change)="toggleField('discount')" />
                <span>{{ 'PURCHASES.DISCOUNT' | translate }}</span>
              </div>
              <div class="field-toggle-item">
                <input type="checkbox" [checked]="isFieldVisible('tax')" (change)="toggleField('tax')" />
                <span>{{ 'PURCHASES.TAX' | translate }}</span>
              </div>
            </div>
            <p-button
              [label]="'COMMON.SAVE' | translate"
              icon="pi pi-check"
              size="small"
              (onClick)="saveFieldVisibility()"
            />
          </div>
        }
        @if (items.length > 0) {
          <table class="lines-table">
            <thead>
              <tr>
                <th>{{ 'PURCHASES.PRODUCT' | translate }}</th>
                <th>{{ 'PURCHASES.UNIT' | translate }}</th>
                @if (isFieldVisible('warehouse')) {
                  <th>{{ 'PURCHASES.WAREHOUSE' | translate }}</th>
                }
                <th class="col-num">{{ 'PURCHASES.QUANTITY' | translate }}</th>
                <th class="col-num">{{ 'PURCHASES.UNIT_COST' | translate }}</th>
                @if (isFieldVisible('discount')) {
                  <th class="col-num">{{ 'PURCHASES.DISCOUNT' | translate }}</th>
                }
                @if (isFieldVisible('tax')) {
                  <th>{{ 'PURCHASES.TAX' | translate }}</th>
                }
                <th class="col-num">{{ 'PURCHASES.LINE_TOTAL' | translate }}</th>
                <th></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]="products()"
                      optionLabel="name"
                      optionValue="id"
                      [filter]="true"
                      filterBy="name,name_ar,code"
                      [placeholder]="'PURCHASES.SELECT_PRODUCT' | translate"
                      [style]="{ width: '100%', minWidth: '180px' }"
                      appendTo="body"
                      (onChange)="onStandaloneProductSelect(i, $event.value)"
                      (onFilter)="onProductSearch($event)"
                    />
                  </td>
                  <td>
                    <p-select
                      formControlName="unit_id"
                      [options]="units()"
                      optionLabel="name"
                      optionValue="id"
                      [filter]="true"
                      [placeholder]="'PURCHASES.UNIT' | translate"
                      [style]="{ width: '100%', minWidth: '100px' }"
                      appendTo="body"
                    />
                  </td>
                  @if (isFieldVisible('warehouse')) {
                    <td>
                      <p-select
                        formControlName="warehouse_id"
                        [options]="warehouses()"
                        optionLabel="name"
                        optionValue="id"
                        [filter]="true"
                        [placeholder]="'PURCHASES.WAREHOUSE' | translate"
                        [style]="{ width: '100%', minWidth: '120px' }"
                        appendTo="body"
                        [showClear]="true"
                      />
                    </td>
                  }
                  <td>
                    <p-inputNumber
                      formControlName="quantity"
                      [min]="0.01"
                      mode="decimal"
                      [minFractionDigits]="0"
                      [maxFractionDigits]="4"
                      [style]="{ width: '100%' }"
                    />
                  </td>
                  <td>
                    <p-inputNumber
                      formControlName="unit_cost"
                      [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%' }"
                      />
                    </td>
                  }
                  @if (isFieldVisible('tax')) {
                    <td>
                      <p-select
                        formControlName="tax_rate_id"
                        [options]="taxRates()"
                        optionLabel="name"
                        optionValue="id"
                        [filter]="true"
                        [placeholder]="'PURCHASES.TAX' | translate"
                        [style]="{ width: '100%', minWidth: '100px' }"
                        appendTo="body"
                        [showClear]="true"
                      />
                    </td>
                  }
                  <td class="amount line-total">
                    {{ getStandaloneLineTotal(i) | number:'1.2-2' }}
                  </td>
                  <td>
                    <p-button
                      icon="pi pi-trash"
                      [rounded]="true"
                      [text]="true"
                      severity="danger"
                      size="small"
                      (onClick)="removeStandaloneItem(i)"
                    />
                  </td>
                </tr>
              }
            </tbody>
            <tfoot>
              <tr class="grand-total-row">
                <td [attr.colspan]="4 + (isFieldVisible('warehouse') ? 1 : 0) + (isFieldVisible('discount') ? 1 : 0) + (isFieldVisible('tax') ? 1 : 0)"></td>
                <td class="amount"><strong>{{ standaloneSubtotal | number:'1.2-2' }}</strong></td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        }
      </div>
    }

    <!-- Return Items from Bill -->
    @if (!standaloneMode() && items.length > 0) {
      <div class="lines-section">
        <div class="lines-header">
          <h3>{{ 'PURCHASES.RETURN_ITEMS' | translate }}</h3>
        </div>
        @if (loadingBillItems()) {
          <div class="loading-spinner">
            <i class="pi pi-spin pi-spinner"></i>
            {{ 'COMMON.LOADING' | translate }}
          </div>
        }
        @if (billFullyReturned()) {
          <div class="fully-returned-banner">
            <i class="pi pi-check-circle"></i>
            {{ 'PURCHASES.BILL_FULLY_RETURNED' | translate }}
          </div>
        }
        <table class="lines-table">
          <thead>
            <tr>
              <th>{{ 'PURCHASES.PRODUCT' | translate }}</th>
              <th>{{ 'PURCHASES.UNIT' | translate }}</th>
              <th class="col-num">{{ 'PURCHASES.ORIGINAL_QTY' | translate }}</th>
              <th class="col-num">{{ 'PURCHASES.RETURN_QTY' | translate }}</th>
              <th class="col-num">{{ 'PURCHASES.UNIT_COST' | translate }}</th>
              <th class="col-num">{{ 'PURCHASES.LINE_TOTAL' | translate }}</th>
            </tr>
          </thead>
          <tbody formArrayName="items">
            @for (item of items.controls; track item; let i = $index) {
              <tr [formGroupName]="i" [class.row-fully-returned]="item.get('fully_returned')?.value">
                <td>
                  {{ item.get('product_name')?.value }}
                  @if (item.get('fully_returned')?.value) {
                    <p-tag value="{{ 'PURCHASES.FULLY_RETURNED' | translate }}" severity="warn" class="returned-tag" />
                  }
                </td>
                <td>{{ item.get('unit_name')?.value }}</td>
                <td class="amount">{{ item.get('original_quantity')?.value }}</td>
                <td>
                  @if (item.get('fully_returned')?.value) {
                    <span class="amount returned-zero">0</span>
                  } @else {
                    <p-inputNumber
                      formControlName="quantity"
                      [min]="0"
                      [max]="item.get('max_quantity')?.value"
                      mode="decimal"
                      [minFractionDigits]="0"
                      [maxFractionDigits]="4"
                      [style]="{ width: '100%' }"
                    />
                  }
                </td>
                <td class="amount">{{ item.get('unit_cost')?.value | number:'1.2-2' }}</td>
                <td class="amount line-total">
                  {{ (item.get('quantity')?.value || 0) * (item.get('unit_cost')?.value || 0) | number:'1.2-2' }}
                </td>
              </tr>
            }
          </tbody>
        </table>
      </div>
    }

    <div class="form-strip secondary" style="margin-top: 0.5rem">
      <div class="form-strip-field grow-2">
        <label>{{ 'PURCHASES.NOTES' | translate }}</label>
        <textarea pTextarea formControlName="notes" rows="1" [autoResize]="true"></textarea>
      </div>
      <div class="form-strip-field grow-2">
        <label>{{ 'PURCHASES.NOTES_AR' | translate }}</label>
        <textarea pTextarea formControlName="notes_ar" rows="1" [autoResize]="true"></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_DRAFT' | translate"
      icon="pi pi-save"
      severity="secondary"
      (onClick)="onSave()"
      [loading]="saving()"
    />
    <p-button
      [label]="'PURCHASES.SAVE_AND_PROCESS' | translate"
      icon="pi pi-bolt"
      (onClick)="onSaveAndProcess()"
      [loading]="saving()"
    />
  </div>
</app-form-dialog>

<!-- View Return Dialog -->
<p-dialog [header]="'PURCHASES.RETURN' | translate" [(visible)]="viewDialogVisible" [modal]="true" [style]="{ width: '850px' }" [closable]="true">
  @if (viewingReturn(); as r) {
    <div class="view-return">
      <div class="view-header-info">
        <div class="info-item"><label>{{ 'PURCHASES.RETURN_NUMBER' | translate }}</label><span class="mono">{{ r.return_number }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.DATE' | translate }}</label><span>{{ r.date }}</span></div>
        <div class="info-item"><label>{{ 'PURCHASES.STATUS' | translate }}</label><p-tag [value]="getStatusLabel(r.status)" [severity]="getStatusSeverity(r.status)" /></div>
        <div class="info-item"><label>{{ 'PURCHASES.SUPPLIER' | translate }}</label><span>{{ r.supplier_name }}</span></div>
        @if (r.bill_number) {
          <div class="info-item"><label>{{ 'PURCHASES.BILL_NUMBER' | translate }}</label><span class="mono">{{ r.bill_number }}</span></div>
        } @else {
          <div class="info-item"><label>{{ 'PURCHASES.RETURN_TYPE' | translate }}</label><p-tag [value]="'PURCHASES.STANDALONE_RETURN' | translate" severity="info" /></div>
        }
        @if (r.warehouse_name) { <div class="info-item"><label>{{ 'PURCHASES.WAREHOUSE' | translate }}</label><span>{{ r.warehouse_name }}</span></div> }
      </div>

      @if (r.reason || r.reason_ar) {
        <div class="view-description">
          @if (r.reason) { <label>{{ 'PURCHASES.REASON' | translate }}</label><p>{{ r.reason }}</p> }
          @if (r.reason_ar) { <label>{{ 'PURCHASES.REASON_AR' | translate }}</label><p>{{ r.reason_ar }}</p> }
        </div>
      }

      @if (r.journal_entry_id) {
        <div class="je-section">
          @if (jeLoading()) {
            <div class="je-loading"><i class="pi pi-spin pi-spinner"></i></div>
          } @else if (journalEntry(); as je) {
            <div class="je-block">
              <div class="je-block-header">
                <i class="pi pi-book"></i>
                <span class="je-block-title">{{ 'PURCHASES.PURCHASE_ENTRY' | 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>{{ 'PURCHASES.JE_ACCOUNT' | translate }}</th>
                      <th class="text-end">{{ 'PURCHASES.JE_DEBIT' | translate }}</th>
                      <th class="text-end">{{ 'PURCHASES.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>
          }
        </div>
      }

      <table class="view-lines-table">
        <thead>
          <tr><th>#</th><th>{{ 'PURCHASES.PRODUCT' | translate }}</th><th>{{ 'PURCHASES.UNIT' | translate }}</th><th>{{ 'PURCHASES.QUANTITY' | translate }}</th><th>{{ 'PURCHASES.UNIT_COST' | translate }}</th><th>{{ 'PURCHASES.LINE_TOTAL' | translate }}</th></tr>
        </thead>
        <tbody>
          @for (item of r.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_cost | number:'1.2-2' }}</td>
              <td class="amount">{{ item.line_total | number:'1.2-2' }}</td>
            </tr>
          }
        </tbody>
        <tfoot>
          <tr class="grand-total-row"><td colspan="4"></td><td><strong>{{ 'PURCHASES.TOTAL' | translate }}</strong></td><td class="amount"><strong>{{ r.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>
