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

<div class="payments-page">
  <app-page-header title="SALES.PAYMENTS" subtitle="SALES.TITLE" (refresh)="retry()">
    <p-button
      [label]="'SALES.SETTLE_INVOICES' | translate"
      icon="pi pi-wallet"
      (onClick)="openSettleDialog()"
    />
  </app-page-header>

  <ng-template #bodyTpl let-pay>
    <tr>
      <td class="mono">{{ pay.payment_number }}</td>
      <td>{{ pay.date }}</td>
      <td class="mono">{{ pay.invoice?.invoice_number || '-' }}</td>
      <td>{{ pay.partner?.name || '-' }}</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>
        <div class="action-buttons">
          <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="info" (onClick)="viewPayment(pay)" [pTooltip]="'COMMON.VIEW' | translate" />
          @if (pay.status === 'draft') {
            <p-button icon="pi pi-check-circle" [rounded]="true" [text]="true" severity="success" (onClick)="postPayment(pay)" [pTooltip]="'SALES.POST' | translate" />
            <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="deletePayment(pay)" [pTooltip]="'COMMON.DELETE' | translate" />
          }
          @if (pay.status !== 'cancelled') {
            <p-button icon="pi pi-ban" [rounded]="true" [text]="true" severity="danger" (onClick)="cancelPayment(pay)" [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"
  />
</div>

<!-- View Payment Dialog -->
<p-dialog
  [header]="'SALES.PAYMENT' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '650px' }"
  [closable]="true"
>
  @if (viewingPayment(); as pay) {
    <div class="view-payment">
      <div class="view-header-info">
        <div class="info-item">
          <label>{{ 'SALES.PAYMENT_NUMBER' | translate }}</label>
          <span class="mono">{{ pay.payment_number }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.DATE' | translate }}</label>
          <span>{{ pay.date }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.STATUS' | translate }}</label>
          <p-tag [value]="getStatusLabel(pay.status)" [severity]="getStatusSeverity(pay.status)" />
        </div>
        <div class="info-item">
          <label>{{ 'SALES.AMOUNT' | translate }}</label>
          <span class="amount-big">{{ pay.amount | number:'1.2-2' }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'SALES.PAYMENT_METHOD' | translate }}</label>
          <span>{{ getPaymentMethodLabel(pay.payment_method) }}</span>
        </div>
        @if (pay.invoice) {
          <div class="info-item">
            <label>{{ 'SALES.INVOICE' | translate }}</label>
            <span class="mono">{{ pay.invoice.invoice_number }}</span>
          </div>
        }
        @if (pay.partner) {
          <div class="info-item">
            <label>{{ 'SALES.CUSTOMER' | translate }}</label>
            <span>{{ pay.partner.name }}</span>
          </div>
        }
        @if (pay.bank_account) {
          <div class="info-item">
            <label>{{ 'SALES.BANK_ACCOUNT' | translate }}</label>
            <span>{{ pay.bank_account.bank_name }} - {{ pay.bank_account.account_number }}</span>
          </div>
        }
        @if (pay.receiving_account) {
          <div class="info-item">
            <label>{{ 'SALES.RECEIVING_ACCOUNT' | translate }}</label>
            <span>{{ pay.receiving_account.code }} - {{ pay.receiving_account.name }}</span>
          </div>
        }
        @if (pay.check_number) {
          <div class="info-item">
            <label>{{ 'SALES.CHECK_NUMBER' | translate }}</label>
            <span class="mono">{{ pay.check_number }}</span>
          </div>
        }
        @if (pay.reference) {
          <div class="info-item">
            <label>{{ 'SALES.REFERENCE' | translate }}</label>
            <span>{{ pay.reference }}</span>
          </div>
        }
        @if (pay.journal_entry) {
          <div class="info-item">
            <label>{{ 'SALES.JOURNAL_ENTRIES' | translate }}</label>
            <span class="mono">#{{ pay.journal_entry.id }} - {{ pay.journal_entry.entry_number }}</span>
          </div>
        }
      </div>
      @if (pay.notes) {
        <div class="view-notes">
          <label>{{ 'SALES.NOTES' | translate }}</label>
          <p>{{ pay.notes }}</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>

<!-- Settlement Dialog -->
<p-dialog
  [header]="'SALES.SETTLE_INVOICES' | translate"
  [(visible)]="settleDialogVisible"
  [modal]="true"
  [style]="{ width: '850px' }"
  [closable]="true"
>
  <div class="settle-form">
    <!-- Top form fields -->
    <div class="settle-grid">
      <div class="settle-field">
        <label>{{ 'SALES.CUSTOMER' | translate }} *</label>
        <p-select
          [ngModel]="settleCustomerId()"
          (ngModelChange)="onSettleCustomerChange($event)"
          [options]="customers()"
          optionLabel="name"
          optionValue="id"
          [filter]="true"
          filterBy="name,code"
          [placeholder]="'COMMON.SELECT' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
        />
        @if (partnerBalance() !== null) {
          <span class="partner-balance" [class.credit]="partnerBalance()! < 0">
            {{ 'COMMON.BALANCE' | translate }}: {{ partnerBalance()! | number:'1.2-2' }}
            @if (partnerBalance()! < 0) { ({{ 'SALES.CREDIT_BALANCE' | translate }}) }
          </span>
        }
        @if (partnerBalanceLoading()) {
          <span class="partner-balance">...</span>
        }
      </div>
      <div class="settle-field">
        <label>{{ 'SALES.DATE' | translate }} *</label>
        <p-datepicker [(ngModel)]="settleDate" dateFormat="yy-mm-dd" [style]="{ width: '100%' }" appendTo="body" />
      </div>
      @if (partnerBalance() !== null && (partnerBalance()! - totalOutstanding()) < 0 && outstandingInvoices().length > 0) {
        <div class="settle-field settle-from-balance-field">
          <label>
            <input type="checkbox" [checked]="settleFromBalance()" (change)="toggleSettleFromBalance($any($event.target).checked)" />
            {{ 'SALES.SETTLE_FROM_BALANCE' | translate }}
          </label>
          <span class="balance-hint">{{ 'SALES.SETTLE_FROM_BALANCE_HINT' | translate:{ amount: ((partnerBalance()! * -1 + totalOutstanding()) | number:'1.2-2') } }}</span>
        </div>
      }
      @if (!settleFromBalance()) {
        <div class="settle-field">
          <label>{{ 'SALES.AMOUNT' | translate }} *</label>
          <p-inputNumber
            [ngModel]="settleAmount()"
            (ngModelChange)="onSettleAmountChange($event)"
            [minFractionDigits]="2"
            [min]="0.01"
            [style]="{ width: '100%' }"
          />
        </div>
        <div class="settle-field">
          <label>{{ 'SALES.PAYMENT_METHOD' | translate }}</label>
          <p-select
            [ngModel]="settlePaymentMethod()"
            (ngModelChange)="onSettleMethodChange($event)"
            [options]="paymentMethods"
            optionLabel="label"
            optionValue="value"
            [style]="{ width: '100%' }"
            appendTo="body"
          >
            <ng-template #selectedItem let-item>
              <span>{{ item.label | translate }}</span>
            </ng-template>
            <ng-template #item let-item>
              <span>{{ item.label | translate }}</span>
            </ng-template>
          </p-select>
        </div>
        <div class="settle-field">
          <label>{{ 'SALES.RECEIVING_ACCOUNT' | translate }} *</label>
          <p-select
            [ngModel]="settleAccountId()"
            (ngModelChange)="onSettleAccountChange($event)"
            [options]="paymentAccountOptions()"
            optionLabel="label"
            optionValue="value"
            [placeholder]="'COMMON.SELECT' | translate"
            [style]="{ width: '100%' }"
            appendTo="body"
          />
        </div>
      }
      <div class="settle-field">
        <label>{{ 'SALES.NOTES' | translate }}</label>
        <input pInputText [ngModel]="settleNotes()" (ngModelChange)="settleNotes.set($event)" style="width: 100%" />
      </div>
    </div>

    <!-- Outstanding invoices -->
    @if (settleLoading()) {
      <div class="settle-loading">
        <p-progressSpinner strokeWidth="3" [style]="{ width: '40px', height: '40px' }" />
      </div>
    } @else if (outstandingInvoices().length > 0) {
      <div class="settle-summary">
        <div class="summary-item">
          <span class="summary-label">{{ 'SALES.TOTAL_OUTSTANDING' | translate }}</span>
          <span class="summary-value outstanding">{{ totalOutstanding() | number:'1.2-2' }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">{{ 'SALES.TOTAL_ALLOCATED' | translate }}</span>
          <span class="summary-value allocated">{{ totalAllocated() | number:'1.2-2' }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">{{ 'SALES.REMAINING' | translate }}</span>
          <span class="summary-value" [class.over]="remainingAmount() < 0" [class.allocated]="remainingAmount() > 0">{{ remainingAmount() | number:'1.2-2' }}</span>
          @if (remainingAmount() > 0) {
            <span class="summary-hint">{{ 'SALES.EXCESS_TO_BALANCE' | translate }}</span>
          }
        </div>
      </div>

      <table class="settle-table">
        <thead>
          <tr>
            <th>{{ 'SALES.INVOICE_NUMBER' | translate }}</th>
            <th>{{ 'SALES.DATE' | translate }}</th>
            <th>{{ 'SALES.DUE_DATE' | translate }}</th>
            <th class="text-end">{{ 'SALES.TOTAL' | translate }}</th>
            <th class="text-end">{{ 'SALES.PAID' | translate }}</th>
            <th class="text-end">{{ 'SALES.BALANCE_DUE' | translate }}</th>
            <th class="text-end">{{ 'SALES.ALLOCATED_AMOUNT' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (inv of outstandingInvoices(); track inv.id; let i = $index) {
            <tr [class.fully-allocated]="inv.allocated >= inv.balance_due">
              <td class="mono">{{ inv.invoice_number }}</td>
              <td>{{ inv.date }}</td>
              <td>{{ inv.due_date }}</td>
              <td class="text-end">{{ inv.total | number:'1.2-2' }}</td>
              <td class="text-end">{{ inv.amount_paid | number:'1.2-2' }}</td>
              <td class="text-end fw-600">{{ inv.balance_due | number:'1.2-2' }}</td>
              <td class="text-end">
                <p-inputNumber
                  [ngModel]="inv.allocated"
                  (ngModelChange)="onAllocationChange(i, $event)"
                  [minFractionDigits]="2"
                  [min]="0"
                  [max]="inv.balance_due"
                  [style]="{ width: '120px' }"
                  inputStyleClass="text-end"
                />
              </td>
            </tr>
          }
        </tbody>
      </table>
    } @else if (settleCustomerId()) {
      <div class="settle-empty">
        <i class="pi pi-check-circle"></i>
        <p>{{ 'SALES.NO_OUTSTANDING_INVOICES' | translate }}</p>
      </div>
    }
  </div>

  <ng-template #footer>
    <div class="settle-footer">
      <p-button
        [label]="'COMMON.CANCEL' | translate"
        icon="pi pi-times"
        severity="secondary"
        (onClick)="settleDialogVisible.set(false)"
      />
      <p-button
        [label]="'SALES.SETTLE_AND_POST' | translate"
        icon="pi pi-check"
        (onClick)="saveSettlement()"
        [loading]="settleSaving()"
        [disabled]="totalAllocated() <= 0 || (settleFromBalance() ? !selectedPartnerArAccountId() : !settleAccountId())"
      />
    </div>
  </ng-template>
</p-dialog>
