<div class="cash-movement-page">
  <app-page-header title="CASH_MOVEMENT.TITLE" subtitle="CASH_MOVEMENT.SUBTITLE" (refresh)="generate()">
  </app-page-header>

  <!-- Filter Bar -->
  <div class="filter-bar">
    <div class="filter-row">
      <div class="filter-field">
        <label>{{ 'CASH_MOVEMENT.ACCOUNT_TYPE' | translate }}</label>
        <p-multiselect
          [ngModel]="selectedTypes()"
          (ngModelChange)="selectedTypes.set($event)"
          [options]="accountTypeOptions"
          optionLabel="label"
          optionValue="value"
          [placeholder]="'CASH_MOVEMENT.SELECT_TYPE' | translate"
          [showToggleAll]="false"
        />
      </div>
      <div class="filter-field">
        <label>{{ 'CASH_MOVEMENT.ACCOUNT' | translate }}</label>
        <p-select
          [ngModel]="selectedAccountId()"
          (ngModelChange)="selectedAccountId.set($event)"
          [options]="filteredAccounts()"
          optionLabel="name"
          optionValue="accountId"
          [filter]="true"
          filterBy="name"
          [showClear]="true"
          [placeholder]="'CASH_MOVEMENT.ALL_ACCOUNTS' | translate"
        />
      </div>
      <div class="filter-field">
        <label>{{ 'CASH_MOVEMENT.DATE_FROM' | translate }}</label>
        <p-datepicker [ngModel]="dateFrom()" (ngModelChange)="dateFrom.set($event)" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="filter-field">
        <label>{{ 'CASH_MOVEMENT.DATE_TO' | translate }}</label>
        <p-datepicker [ngModel]="dateTo()" (ngModelChange)="dateTo.set($event)" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
    </div>
    <div class="filter-actions">
      <div class="date-presets">
        <p-button [label]="'CASH_MOVEMENT.TODAY' | translate" [text]="true" size="small" (onClick)="setToday()" />
        <p-button [label]="'CASH_MOVEMENT.THIS_MONTH' | translate" [text]="true" size="small" (onClick)="setThisMonth()" />
        <p-button [label]="'CASH_MOVEMENT.THIS_YEAR' | translate" [text]="true" size="small" (onClick)="setThisYear()" />
      </div>
      <div class="action-buttons">
        <p-button [label]="'CASH_MOVEMENT.GENERATE' | translate" icon="pi pi-play" (onClick)="generate()" [loading]="loading()" />
        @if (loaded()) {
          <p-button icon="pi pi-print" [text]="true" [pTooltip]="'CASH_MOVEMENT.PRINT' | translate" (onClick)="printReport()" />
          <p-button icon="pi pi-file-excel" [text]="true" severity="success" [pTooltip]="'CASH_MOVEMENT.EXPORT_EXCEL' | translate" (onClick)="exportExcel()" />
          <p-button icon="pi pi-file-pdf" [text]="true" severity="danger" [pTooltip]="'CASH_MOVEMENT.EXPORT_PDF' | translate" (onClick)="exportPdf()" />
        }
      </div>
    </div>
  </div>

  <!-- Loading -->
  @if (loading()) {
    <div class="loading-container">
      <p-progressSpinner strokeWidth="3" />
    </div>
  }

  <!-- Results -->
  @if (loaded() && !loading()) {
    <!-- Summary Cards -->
    <div class="summary-cards">
      <div class="summary-card">
        <span class="label">{{ 'CASH_MOVEMENT.OPENING_BALANCE' | translate }}</span>
        <span class="value">{{ totalOpening() | number:'1.2-2' }}</span>
      </div>
      <div class="summary-card inflow">
        <span class="label">{{ 'CASH_MOVEMENT.TOTAL_INFLOWS' | translate }}</span>
        <span class="value">{{ totalInflows() | number:'1.2-2' }}</span>
      </div>
      <div class="summary-card outflow">
        <span class="label">{{ 'CASH_MOVEMENT.TOTAL_OUTFLOWS' | translate }}</span>
        <span class="value">{{ totalOutflows() | number:'1.2-2' }}</span>
      </div>
      <div class="summary-card closing">
        <span class="label">{{ 'CASH_MOVEMENT.CLOSING_BALANCE' | translate }}</span>
        <span class="value">{{ totalClosing() | number:'1.2-2' }}</span>
      </div>
    </div>

    <!-- Per-Account Panels -->
    @for (ledger of accountLedgers(); track ledger.account.accountId) {
      <p-panel [toggleable]="true" [collapsed]="false" styleClass="account-panel">
        <ng-template #header>
          <div class="panel-header">
            <div class="panel-title">
              <span class="account-name">{{ ledger.account.name }}</span>
              <p-tag [value]="getTypeBadge(ledger.account.type).label" [severity]="getTypeBadge(ledger.account.type).severity" />
            </div>
            <div class="panel-balances">
              <span class="opening">{{ 'CASH_MOVEMENT.OPENING' | translate }}: {{ ledger.openingBalance | number:'1.2-2' }}</span>
              <span class="closing">{{ 'CASH_MOVEMENT.CLOSING' | translate }}: {{ ledger.closingBalance | number:'1.2-2' }}</span>
            </div>
          </div>
        </ng-template>

        <p-table [value]="ledger.entries" [scrollable]="true" styleClass="p-datatable-sm p-datatable-striped">
          <ng-template #header>
            <tr>
              <th style="width:50px">#</th>
              <th>{{ 'CASH_MOVEMENT.DATE' | translate }}</th>
              <th>{{ 'CASH_MOVEMENT.SOURCE' | translate }}</th>
              <th>{{ 'CASH_MOVEMENT.DOCUMENT' | translate }}</th>
              <th>{{ 'CASH_MOVEMENT.DESCRIPTION' | translate }}</th>
              <th class="text-end">{{ 'CASH_MOVEMENT.DEBIT' | translate }}</th>
              <th class="text-end">{{ 'CASH_MOVEMENT.CREDIT' | translate }}</th>
              <th class="text-end">{{ 'CASH_MOVEMENT.BALANCE' | translate }}</th>
              <th style="width:50px"></th>
            </tr>
          </ng-template>
          <ng-template #body let-entry let-i="rowIndex">
            <tr>
              <td>{{ i + 1 }}</td>
              <td>{{ entry.date }}</td>
              <td>
                <p-tag
                  [value]="getSourceInfo(entry).label"
                  [severity]="getSourceInfo(entry).severity"
                />
              </td>
              <td>
                <a class="doc-link" (click)="navigateToSource(entry)">{{ getDocNumber(entry) }}</a>
              </td>
              <td>{{ entry.description || entry.entry_description || '—' }}</td>
              <td class="text-end amount-cell debit">{{ +entry.debit ? (entry.debit | number:'1.2-2') : '' }}</td>
              <td class="text-end amount-cell credit">{{ +entry.credit ? (entry.credit | number:'1.2-2') : '' }}</td>
              <td class="text-end amount-cell">{{ getRunningBalance(ledger, i) | number:'1.2-2' }}</td>
              <td>
                <p-button
                  icon="pi pi-info-circle"
                  [rounded]="true"
                  [text]="true"
                  size="small"
                  (onClick)="showJeDetail(entry.journal_entry_id)"
                  [pTooltip]="'CASH_MOVEMENT.JE_DETAIL' | translate"
                />
              </td>
            </tr>
          </ng-template>
          <ng-template #footer>
            <tr class="totals-row">
              <td colspan="5" class="text-end"><strong>{{ 'CASH_MOVEMENT.TOTALS' | translate }}</strong></td>
              <td class="text-end"><strong>{{ ledger.totalDebit | number:'1.2-2' }}</strong></td>
              <td class="text-end"><strong>{{ ledger.totalCredit | number:'1.2-2' }}</strong></td>
              <td class="text-end"><strong>{{ ledger.closingBalance | number:'1.2-2' }}</strong></td>
              <td></td>
            </tr>
          </ng-template>
        </p-table>
      </p-panel>
    }

    @if (accountLedgers().length === 0) {
      <div class="empty-state">
        <i class="pi pi-inbox"></i>
        <p>{{ 'CASH_MOVEMENT.NO_DATA' | translate }}</p>
      </div>
    }
  }

  @if (!loaded() && !loading()) {
    <div class="empty-state">
      <i class="pi pi-chart-line"></i>
      <p>{{ 'CASH_MOVEMENT.EMPTY_STATE' | translate }}</p>
    </div>
  }
</div>

<!-- JE Detail Dialog -->
<p-dialog
  [header]="'CASH_MOVEMENT.JE_DETAIL' | translate"
  [(visible)]="jeDialogVisible"
  [modal]="true"
  [style]="{ width: '550px' }"
  [closable]="true"
>
  @if (jeLoading()) {
    <div class="je-loading"><p-progressSpinner strokeWidth="3" /></div>
  } @else if (jeDetail(); as je) {
    <div class="je-detail-content">
      <div class="je-header-info">
        <span class="je-number">{{ je.entry_number }}</span>
        <p-tag [value]="je.status" [severity]="je.status === 'posted' ? 'success' : 'warn'" />
      </div>
      <div class="je-meta">
        <div><label>{{ 'CASH_MOVEMENT.DATE' | translate }}:</label> {{ je.date }}</div>
        @if (je.description) {
          <div><label>{{ 'CASH_MOVEMENT.DESCRIPTION' | translate }}:</label> {{ je.description }}</div>
        }
      </div>
      @if (je.lines?.length) {
        <table class="je-lines-table">
          <thead>
            <tr>
              <th>{{ 'CASH_MOVEMENT.JE_ACCOUNT' | translate }}</th>
              <th class="text-end">{{ 'CASH_MOVEMENT.DEBIT' | translate }}</th>
              <th class="text-end">{{ 'CASH_MOVEMENT.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>
  }
</p-dialog>
