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

<div class="vouchers-page">
  <app-page-header title="VOUCHERS.RECEIPT_TITLE" subtitle="VOUCHERS.RECEIPT_SUBTITLE" (refresh)="retry()">
    @if (autoApprove) {
      <p-tag [value]="'COMMON.QUICK_MODE' | translate" severity="success" icon="pi pi-bolt" />
    } @else {
      <p-tag [value]="'COMMON.COMPLETE_MODE' | translate" severity="info" icon="pi pi-list-check" />
    }
    <p-button [label]="'VOUCHERS.NEW_RECEIPT' | translate" icon="pi pi-plus" (onClick)="openNew()" />
  </app-page-header>

  <ng-template #bodyTpl let-item>
    <tr>
      <td>{{ item.voucher_number }}</td>
      <td>{{ item.date }}</td>
      <td>{{ item.partner?.name || '—' }}</td>
      <td class="text-end">{{ item.total_amount | number:'1.2-2' }}</td>
      <td>{{ item.payment_method_label }}</td>
      <td>
        <p-tag [value]="item.status_label" [severity]="getStatusSeverity(item.status)" />
      </td>
      <td>
        <div class="action-buttons">
          <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="secondary" (onClick)="viewVoucher(item)" [pTooltip]="'COMMON.VIEW' | translate" />
          <p-button icon="pi pi-print" [rounded]="true" [text]="true" severity="secondary" (onClick)="printVoucher(item)" [pTooltip]="'COMMON.PRINT' | translate" />
          @if (item.status !== 'cancelled') {
            <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" (onClick)="edit(item)" [pTooltip]="'COMMON.EDIT' | translate" />
          }
          @if (item.status === 'approved') {
            <p-button icon="pi pi-ban" [rounded]="true" [text]="true" severity="warn" (onClick)="cancelVoucher(item)" [pTooltip]="'VOUCHERS.CANCEL_VOUCHER' | translate" />
          }
          @if (item.status !== 'cancelled') {
            <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="delete(item)" [pTooltip]="'COMMON.DELETE' | translate" />
          }
        </div>
      </td>
    </tr>
  </ng-template>

  <app-data-table
    [data]="items()"
    [loading]="loading()"
    [error]="null"
    (retry)="retry()"
    [columns]="columns"
    [bodyTpl]="bodyTpl"
  />
</div>

<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editing() ? ('VOUCHERS.EDIT_RECEIPT' | translate) : ('VOUCHERS.NEW_RECEIPT' | translate)"
  [saving]="saving()"
  (save)="onSave()"
>
  <form [formGroup]="form" class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'VOUCHERS.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-field">
        <label>{{ 'VOUCHERS.AMOUNT' | translate }} *</label>
        <p-inputNumber formControlName="total_amount" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="2" />
      </div>
    </div>
    <div class="form-field">
      <label>{{ 'VOUCHERS.PARTNER' | translate }}</label>
      <p-select formControlName="partner_id" [options]="clients()" optionLabel="name" optionValue="id"
        [filter]="true" filterBy="name,code" [showClear]="true" [placeholder]="'VOUCHERS.SELECT_PARTNER' | translate"
        (onChange)="onPartnerChange($event.value)" />
      @if (partnerBalanceLoading()) {
        <small class="partner-balance loading"><i class="pi pi-spin pi-spinner"></i> {{ 'VOUCHERS.LOADING_BALANCE' | translate }}</small>
      } @else if (partnerBalance() !== null) {
        <small class="partner-balance" [class.positive]="partnerBalance()! > 0" [class.negative]="partnerBalance()! < 0" [class.zero]="partnerBalance()! === 0">
          <i class="pi pi-wallet"></i> {{ 'VOUCHERS.PARTNER_BALANCE' | translate }}: {{ partnerBalance() | number:'1.2-2' }}
        </small>
      }
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'VOUCHERS.PAYMENT_METHOD' | translate }} *</label>
        <p-select formControlName="payment_method" [options]="paymentMethods" optionLabel="label" optionValue="value" (onChange)="onPaymentMethodChange($event.value)" />
      </div>
      <div class="form-field">
        <label>{{ 'VOUCHERS.RECEIVING_ACCOUNT' | translate }} *</label>
        <p-select formControlName="receiving_account_id" [options]="paymentAccountOptions()" optionLabel="label" optionValue="value"
          [filter]="true" filterBy="label" [showClear]="true" (onChange)="onAccountChange($event.value)" />
      </div>
    </div>
    @if (form.get('payment_method')?.value === 'check') {
      <div class="form-row">
        <div class="form-field">
          <label>{{ 'VOUCHERS.CHECK_NUMBER' | translate }}</label>
          <input pInputText formControlName="check_number" />
        </div>
        <div class="form-field">
          <label>{{ 'VOUCHERS.CHECK_DATE' | translate }}</label>
          <p-datepicker formControlName="check_date" dateFormat="yy-mm-dd" [showIcon]="true" />
        </div>
      </div>
      <div class="form-field">
        <label>{{ 'VOUCHERS.CHECK_BANK' | translate }}</label>
        <input pInputText formControlName="check_bank" />
      </div>
    }
    <div class="form-field">
      <label>{{ 'VOUCHERS.DESCRIPTION' | translate }}</label>
      <textarea pTextarea formControlName="description" rows="3"></textarea>
    </div>
  </form>
</app-form-dialog>

<!-- View Dialog -->
<p-dialog
  [header]="'VOUCHERS.VIEW_RECEIPT' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '650px' }"
  [closable]="true"
>
  @if (viewing(); as v) {
    <div class="view-dialog">
      <div class="view-header">
        <span class="voucher-number">{{ v.voucher_number }}</span>
        <p-tag [value]="v.status_label" [severity]="getStatusSeverity(v.status)" />
      </div>
      <div class="view-grid">
        <div class="view-item">
          <label>{{ 'VOUCHERS.DATE' | translate }}</label>
          <span>{{ v.date }}</span>
        </div>
        <div class="view-item">
          <label>{{ 'VOUCHERS.AMOUNT' | translate }}</label>
          <span class="amount">{{ v.total_amount | number:'1.2-2' }}</span>
        </div>
        <div class="view-item">
          <label>{{ 'VOUCHERS.PARTNER' | translate }}</label>
          <span>{{ v.partner?.name || '—' }}</span>
        </div>
        <div class="view-item">
          <label>{{ 'VOUCHERS.PAYMENT_METHOD' | translate }}</label>
          <span>{{ v.payment_method_label }}</span>
        </div>
        <div class="view-item">
          <label>{{ 'VOUCHERS.RECEIVING_ACCOUNT' | translate }}</label>
          <span>{{ v.receiving_account?.name || v.receiving_account?.name_ar || '—' }}</span>
        </div>
        @if (v.bank_account) {
          <div class="view-item">
            <label>{{ 'VOUCHERS.BANK_ACCOUNT' | translate }}</label>
            <span>{{ v.bank_account?.bank_name || '—' }}</span>
          </div>
        }
        @if (v.check_number) {
          <div class="view-item">
            <label>{{ 'VOUCHERS.CHECK_NUMBER' | translate }}</label>
            <span>{{ v.check_number }}</span>
          </div>
          <div class="view-item">
            <label>{{ 'VOUCHERS.CHECK_DATE' | translate }}</label>
            <span>{{ v.check_date || '—' }}</span>
          </div>
          <div class="view-item">
            <label>{{ 'VOUCHERS.CHECK_BANK' | translate }}</label>
            <span>{{ v.check_bank || '—' }}</span>
          </div>
        }
        @if (v.currency) {
          <div class="view-item">
            <label>{{ 'VOUCHERS.CURRENCY' | translate }}</label>
            <span>{{ v.currency.code }} ({{ v.currency.symbol }})</span>
          </div>
        }
      </div>
      @if (v.description) {
        <div class="view-section">
          <label>{{ 'VOUCHERS.DESCRIPTION' | translate }}</label>
          <p>{{ v.description }}</p>
        </div>
      }
      @if (v.journal_entry_id) {
        <div class="view-section je-section">
          <label>{{ 'VOUCHERS.JOURNAL_ENTRY' | translate }}</label>
          @if (viewJeLoading()) {
            <div class="je-loading"><i class="pi pi-spin pi-spinner"></i></div>
          } @else if (viewJournalEntry(); as je) {
            <div class="je-info">
              <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">
                <thead>
                  <tr>
                    <th>{{ 'VOUCHERS.JE_ACCOUNT' | translate }}</th>
                    <th>{{ 'VOUCHERS.JE_DEBIT' | translate }}</th>
                    <th>{{ 'VOUCHERS.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 class="view-footer">
        <small>{{ 'VOUCHERS.CREATED_AT' | translate }}: {{ v.created_at }}</small>
        @if (v.approved_at) {
          <small>{{ 'VOUCHERS.APPROVED_AT' | translate }}: {{ v.approved_at }}</small>
        }
      </div>
      @if (v.status === 'approved') {
        <div class="view-actions">
          <p-button [label]="'VOUCHERS.CANCEL_VOUCHER' | translate" icon="pi pi-ban" severity="danger" [outlined]="true" (onClick)="cancelVoucher(v)" [loading]="saving()" />
        </div>
      }
    </div>
  }
</p-dialog>
