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

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

  <ng-template #bodyTpl let-ret>
    <tr>
      <td class="mono">{{ ret.return_number }}</td>
      <td>{{ ret.date }}</td>
      <td class="mono">{{ ret.invoice_number || '-' }}</td>
      <td>{{ ret.customer_name }}</td>
      <td class="amount">{{ ret.total | number:'1.2-2' }}</td>
      <td>
        <p-tag
          [value]="getStatusLabel(ret.status)"
          [severity]="getStatusSeverity(ret.status)"
        />
      </td>
      <td>
        <div class="action-buttons">
          <p-button
            icon="pi pi-eye"
            [rounded]="true"
            [text]="true"
            severity="info"
            (onClick)="viewReturn(ret)"
            [pTooltip]="'COMMON.VIEW' | translate"
          />
          <p-button
            icon="pi pi-print"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="printReturn(ret)"
            [pTooltip]="'SALES.PRINT' | translate"
          />
          @if (ret.status === 'draft' || ret.status === 'pending_approval' || ret.status === 'approved') {
            <p-button
              icon="pi pi-bolt"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="quickProcess(ret)"
              [pTooltip]="'SALES.QUICK_PROCESS' | translate"
            />
          }
          @if (ret.status === 'draft') {
            <p-button
              icon="pi pi-pencil"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="editReturn(ret)"
              [pTooltip]="'COMMON.EDIT' | translate"
            />
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="deleteReturn(ret)"
              [pTooltip]="'COMMON.DELETE' | translate"
            />
          }
          @if (ret.status !== 'cancelled' && ret.status !== 'posted') {
            <p-button
              icon="pi pi-ban"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="cancelReturn(ret)"
              [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 Return Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingReturn() ? ('SALES.EDIT_RETURN' | translate) : ('SALES.NEW_RETURN' | translate)"
  width="80vw"
  [saving]="saving()"
  [showFooter]="false"
>
  <form [formGroup]="returnForm" class="return-form">
    <div class="form-grid">
      <div class="form-field span-4" style="margin-bottom: 0.5rem;">
        <div class="standalone-toggle">
          <p-button
            [label]="(standaloneMode() ? 'SALES.INVOICE_RETURN' : 'SALES.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">{{ 'SALES.STANDALONE_HINT' | translate }}</span>
          }
        </div>
      </div>
    </div>

    <div class="form-grid">
      @if (!standaloneMode()) {
      <div class="form-field span-2">
        <label>{{ 'SALES.INVOICE' | translate }} *</label>
        <p-select
          formControlName="invoice_id"
          [options]="invoices()"
          optionLabel="invoice_number"
          optionValue="id"
          [filter]="true"
          filterBy="invoice_number,customer_name"
          [placeholder]="'SALES.SELECT_INVOICE' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
          (onChange)="onInvoiceSelect($event.value)"
        >
          <ng-template #item let-inv>
            <span>{{ inv.invoice_number }} — {{ inv.customer_name }} ({{ inv.total | number:'1.2-2' }})</span>
          </ng-template>
          <ng-template #selectedItem let-inv>
            <span>{{ inv.invoice_number }} — {{ inv.customer_name }}</span>
          </ng-template>
        </p-select>
      </div>
      } @else {
      <div class="form-field span-2">
        <label>{{ 'SALES.CUSTOMER' | translate }} *</label>
        <p-select
          formControlName="customer_id"
          [options]="customers()"
          optionLabel="name"
          optionValue="id"
          [filter]="true"
          filterBy="name,code"
          [placeholder]="'SALES.SELECT_CUSTOMER' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
        />
      </div>
      }
      <div class="form-field">
        <label>{{ 'SALES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
    </div>

    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'SALES.REASON' | translate }} *</label>
        <input pInputText formControlName="reason" />
      </div>
      <div class="form-field span-2">
        <label>{{ 'SALES.REASON_AR' | translate }}</label>
        <input pInputText formControlName="reason_ar" />
      </div>
    </div>

    <!-- Return Items from Invoice -->
    @if (!standaloneMode()) {
    @if (items.length > 0) {
      <div class="lines-section">
        <div class="lines-header">
          <h3>{{ 'SALES.RETURN_ITEMS' | translate }}</h3>
        </div>
        @if (loadingInvoiceItems()) {
          <div class="loading-spinner">
            <i class="pi pi-spin pi-spinner"></i>
            {{ 'COMMON.LOADING' | translate }}
          </div>
        }
        @if (invoiceFullyReturned()) {
          <div class="fully-returned-banner">
            <i class="pi pi-check-circle"></i>
            {{ 'SALES.INVOICE_FULLY_RETURNED' | translate }}
          </div>
        }
        <table class="lines-table">
          <thead>
            <tr>
              <th>{{ 'SALES.PRODUCT' | translate }}</th>
              <th>{{ 'SALES.UNIT' | translate }}</th>
              <th class="col-num">{{ 'SALES.ORIGINAL_QTY' | translate }}</th>
              <th class="col-num">{{ 'SALES.RETURN_QTY' | translate }}</th>
              <th class="col-num">{{ 'SALES.UNIT_PRICE' | translate }}</th>
              <th class="col-num">{{ 'SALES.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="{{ 'SALES.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_price')?.value | number:'1.2-2' }}</td>
                <td class="amount line-total">
                  {{ (item.get('quantity')?.value || 0) * (item.get('unit_price')?.value || 0) | number:'1.2-2' }}
                </td>
              </tr>
            }
          </tbody>
        </table>
      </div>
    }
    }

    @if (standaloneMode()) {
      <div class="lines-section">
        <div class="lines-header">
          <h3>{{ 'SALES.RETURN_ITEMS' | translate }}</h3>
          <div style="display: flex; gap: 0.5rem; align-items: center">
            <p-button
              icon="pi pi-cog"
              [rounded]="true"
              [text]="true"
              severity="contrast"
              styleClass="header-add-btn"
              (onClick)="fieldSettingsVisible.set(!fieldSettingsVisible())"
              [pTooltip]="'SALES.FIELD_SETTINGS' | translate"
            />
            <p-button
              [label]="'SALES.ADD_LINE' | translate"
              icon="pi pi-plus"
              severity="contrast"
              size="small"
              styleClass="header-add-btn"
              (onClick)="addStandaloneItem()"
            />
          </div>
        </div>
        @if (fieldSettingsVisible()) {
          <div class="field-settings-panel" style="background: var(--surface-ground, #f8fafc); border: 1px solid var(--surface-border, #e2e8f0); border-radius: 8px; padding: 0.75rem; margin-bottom: 0.5rem; display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;">
            <label style="display: flex; align-items: center; gap: 0.3rem; cursor: pointer; font-size: 0.85rem;">
              <input type="checkbox" [checked]="isFieldVisible('warehouse')" (change)="toggleField('warehouse')" />
              {{ 'SALES.WAREHOUSE' | translate }}
            </label>
            <label style="display: flex; align-items: center; gap: 0.3rem; cursor: pointer; font-size: 0.85rem;">
              <input type="checkbox" [checked]="isFieldVisible('discount')" (change)="toggleField('discount')" />
              {{ 'SALES.DISCOUNT' | translate }}
            </label>
            <label style="display: flex; align-items: center; gap: 0.3rem; cursor: pointer; font-size: 0.85rem;">
              <input type="checkbox" [checked]="isFieldVisible('tax')" (change)="toggleField('tax')" />
              {{ 'SALES.TAX_RATE' | translate }}
            </label>
            <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>{{ 'SALES.PRODUCT' | translate }}</th>
                <th>{{ 'SALES.UNIT' | translate }}</th>
                @if (isFieldVisible('warehouse')) {
                  <th>{{ 'SALES.WAREHOUSE' | translate }}</th>
                }
                <th class="col-num">{{ 'SALES.QUANTITY' | translate }}</th>
                <th class="col-num">{{ 'SALES.UNIT_PRICE' | translate }}</th>
                @if (isFieldVisible('discount')) {
                  <th class="col-num">{{ 'SALES.DISCOUNT' | translate }} %</th>
                }
                @if (isFieldVisible('tax')) {
                  <th>{{ 'SALES.TAX_RATE' | translate }}</th>
                }
                <th class="col-num">{{ 'SALES.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,code"
                      placeholder="..."
                      [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"
                      [style]="{ width: '100%', minWidth: '100px' }"
                      appendTo="body"
                    />
                  </td>
                  @if (isFieldVisible('warehouse')) {
                    <td>
                      <p-select
                        formControlName="warehouse_id"
                        [options]="warehouses()"
                        optionLabel="name"
                        optionValue="id"
                        [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_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%' }"
                      />
                    </td>
                  }
                  @if (isFieldVisible('tax')) {
                    <td>
                      <p-select
                        formControlName="tax_rate_id"
                        [options]="taxRates()"
                        optionLabel="name"
                        optionValue="id"
                        [style]="{ width: '100%', minWidth: '120px' }"
                        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"
                      (onClick)="removeStandaloneItem(i)"
                      [disabled]="items.length <= 1"
                    />
                  </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>
    }

    <div class="form-grid" style="margin-top: 1rem">
      <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_DRAFT' | translate"
      icon="pi pi-save"
      severity="secondary"
      (onClick)="onSave()"
      [loading]="saving()"
    />
    <p-button
      [label]="'SALES.SAVE_AND_PROCESS' | translate"
      icon="pi pi-bolt"
      (onClick)="onSaveAndProcess()"
      [loading]="saving()"
    />
  </div>
</app-form-dialog>

<!-- View Return Dialog -->
<p-dialog
  [header]="'SALES.RETURN' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '850px' }"
  [closable]="true"
>
  @if (viewingReturn(); as ret) {
    <div class="view-return">
      <div class="view-header-info">
        <div class="info-item">
          <label>{{ 'SALES.RETURN_NUMBER' | translate }}</label>
          <span class="mono">{{ ret.return_number }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.DATE' | translate }}</label>
          <span>{{ ret.date }}</span>
        </div>
        @if (ret.invoice_number) {
          <div class="info-item">
            <label>{{ 'SALES.INVOICE_NUMBER' | translate }}</label>
            <a class="invoice-link" [routerLink]="['/sales/invoices']" [queryParams]="{ view: ret.invoice_id }">
              <i class="pi pi-external-link"></i>
              {{ ret.invoice_number }}
            </a>
          </div>
        } @else {
          <div class="info-item">
            <label>{{ 'SALES.RETURN_TYPE' | translate }}</label>
            <p-tag value="{{ 'SALES.STANDALONE_RETURN' | translate }}" severity="info" />
          </div>
        }
        <div class="info-item">
          <label>{{ 'SALES.STATUS' | translate }}</label>
          <p-tag [value]="getStatusLabel(ret.status)" [severity]="getStatusSeverity(ret.status)" />
        </div>
        <div class="info-item">
          <label>{{ 'SALES.CUSTOMER' | translate }}</label>
          <span>{{ ret.customer_name }}</span>
        </div>
        @if (ret.reason) {
          <div class="info-item">
            <label>{{ 'SALES.REASON' | translate }}</label>
            <span>{{ ret.reason }}</span>
          </div>
        }
      </div>

      @if (ret.journal_entry_id || ret.cogs_journal_entry_id) {
        <div class="je-section">
          @if (jeLoading()) {
            <div class="je-loading"><i class="pi pi-spin pi-spinner"></i></div>
          } @else {
            @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>
            }
          }
        </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.LINE_TOTAL' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (item of ret.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 class="amount">{{ item.line_total | number:'1.2-2' }}</td>
            </tr>
          }
        </tbody>
        <tfoot>
          <tr class="grand-total-row">
            <td colspan="5"></td>
            <td><strong>{{ 'SALES.TOTAL' | translate }}</strong></td>
            <td class="amount"><strong>{{ ret.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>
