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

<div class="journal-entries-page">
  <app-page-header title="JOURNAL_ENTRIES.TITLE" subtitle="JOURNAL_ENTRIES.SUBTITLE" (refresh)="retry()">
    <p-button
      [label]="'JOURNAL_ENTRIES.NEW_ENTRY' | translate"
      icon="pi pi-plus"
      (onClick)="openNew()"
    />
  </app-page-header>

  <ng-template #bodyTpl let-entry>
      <tr>
        <td class="mono">{{ entry.entry_number || ('JOURNAL_ENTRIES.DRAFT_NUMBER' | translate) }}</td>
        <td>{{ entry.date }}</td>
        <td>{{ entry.reference }}</td>
        <td>
          @if (entry.source_type) {
            @if (getSourceRoute(entry.source_type)) {
              <p-tag [value]="getSourceLabel(entry.source_type)" severity="info" [rounded]="true"
                class="source-link" (click)="navigateToSource(entry)"
                [pTooltip]="'JOURNAL_ENTRIES.GO_TO_SOURCE' | translate" tooltipPosition="top" />
            } @else {
              <p-tag [value]="getSourceLabel(entry.source_type)" severity="secondary" [rounded]="true" />
            }
          }
        </td>
        <td class="desc-cell">{{ entry.description }}</td>
        <td>{{ entry.fiscal_year?.name || getFiscalYearName(entry.fiscal_year_id) }}</td>
        <td class="amount debit-amount">{{ entry.total_debit | number:'1.2-2' }}</td>
        <td class="amount credit-amount">{{ entry.total_credit | number:'1.2-2' }}</td>
        <td>
          <p-tag
            [value]="'JOURNAL_ENTRIES.STATUS_' + entry.status.toUpperCase() | translate"
            [severity]="getStatusSeverity(entry.status)"
          />
        </td>
        <td>
          <div class="action-buttons">
            <p-button
              icon="pi pi-eye"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="viewEntry(entry)"
              [pTooltip]="'JOURNAL_ENTRIES.VIEW' | translate"
            />
            @if (entry.status === 'draft') {
              <p-button
                icon="pi pi-pencil"
                [rounded]="true"
                [text]="true"
                severity="info"
                (onClick)="editEntry(entry)"
              />
              <p-button
                icon="pi pi-check"
                [rounded]="true"
                [text]="true"
                severity="success"
                (onClick)="approveEntry(entry)"
                [pTooltip]="'JOURNAL_ENTRIES.APPROVE' | translate"
              />
              <p-button
                icon="pi pi-trash"
                [rounded]="true"
                [text]="true"
                severity="danger"
                (onClick)="deleteEntry(entry)"
              />
            }
            @if (entry.status === 'approved') {
              <p-button
                icon="pi pi-upload"
                [rounded]="true"
                [text]="true"
                severity="success"
                (onClick)="postEntry(entry)"
                [pTooltip]="'JOURNAL_ENTRIES.POST' | translate"
              />
            }
            @if (entry.status === 'posted') {
              <p-button
                icon="pi pi-replay"
                [rounded]="true"
                [text]="true"
                severity="warn"
                (onClick)="reverseEntry(entry)"
                [pTooltip]="'JOURNAL_ENTRIES.REVERSE' | translate"
              />
            }
            @if (entry.status === 'draft' || entry.status === 'approved') {
              <p-button icon="pi pi-ban" [rounded]="true" [text]="true" severity="danger"
                (onClick)="cancelEntry(entry)" [pTooltip]="'JOURNAL_ENTRIES.CANCEL' | translate" tooltipPosition="top" />
            }
          </div>
        </td>
      </tr>
    </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"
  >
  </app-data-table>
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingEntry() ? ('JOURNAL_ENTRIES.EDIT_ENTRY' | translate) : ('JOURNAL_ENTRIES.NEW_ENTRY' | translate)"
  width="900px"
  [saving]="!!(saving$ | async)"
  (save)="onSave()"
  [showFooter]="false"
>
  <form [formGroup]="entryForm" class="entry-form">
    <div class="form-header-row">
      <div class="form-field">
        <label>{{ 'JOURNAL_ENTRIES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-field">
        <label>{{ 'JOURNAL_ENTRIES.FISCAL_YEAR' | translate }}</label>
        <p-select
          formControlName="fiscal_year_id"
          [options]="(fiscalYears$ | async) || []"
          optionLabel="name"
          optionValue="id"
          [showClear]="true"
          [placeholder]="'JOURNAL_ENTRIES.SELECT_FISCAL_YEAR' | translate"
          appendTo="body"
        />
      </div>
      <div class="form-field">
        <label>{{ 'JOURNAL_ENTRIES.REFERENCE' | translate }}</label>
        <input pInputText formControlName="reference" />
      </div>
      <div class="form-field grow">
        <label>{{ 'JOURNAL_ENTRIES.DESCRIPTION' | translate }}</label>
        <input pInputText formControlName="description" />
      </div>
    </div>

    <div class="lines-section">
      <div class="lines-header">
        <h3>{{ 'JOURNAL_ENTRIES.LINES' | translate }}</h3>
        <p-button
          icon="pi pi-plus"
          [label]="'JOURNAL_ENTRIES.ADD_LINE' | translate"
          severity="secondary"
          [outlined]="true"
          size="small"
          (onClick)="addLine()"
        />
      </div>

      <table class="lines-table">
        <thead>
          <tr>
            <th class="col-account">{{ 'JOURNAL_ENTRIES.ACCOUNT' | translate }}</th>
            <th class="col-amount">{{ 'JOURNAL_ENTRIES.DEBIT' | translate }}</th>
            <th class="col-amount">{{ 'JOURNAL_ENTRIES.CREDIT' | translate }}</th>
            <th class="col-center">{{ 'JOURNAL_ENTRIES.COST_CENTER' | translate }}</th>
            <th class="col-desc">{{ 'JOURNAL_ENTRIES.LINE_DESC' | translate }}</th>
            <th class="col-action"></th>
          </tr>
        </thead>
        <tbody formArrayName="lines">
          @for (line of lines.controls; track line; let i = $index) {
            <tr [formGroupName]="i">
              <td>
                <p-select
                  formControlName="account_id"
                  [options]="detailAccounts()"
                  optionLabel="name_ar"
                  optionValue="id"
                  [filter]="true"
                  filterBy="name_ar,name_en,code"
                  [placeholder]="'JOURNAL_ENTRIES.SELECT_ACCOUNT' | translate"
                  [style]="{ width: '100%' }"
                  appendTo="body"
                >
                  <ng-template #selectedItem let-selected>
                    <span>{{ selected.code }} - {{ selected.name_ar }}</span>
                  </ng-template>
                  <ng-template #item let-account>
                    <span>{{ account.code }} - {{ account.name_ar }}</span>
                  </ng-template>
                </p-select>
              </td>
              <td>
                <p-inputNumber formControlName="debit" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="2" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-inputNumber formControlName="credit" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="2" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-select
                  formControlName="cost_center_id"
                  [options]="(costCenters$ | async) || []"
                  optionLabel="name_ar"
                  optionValue="id"
                  [showClear]="true"
                  [placeholder]="'JOURNAL_ENTRIES.OPTIONAL' | translate"
                  [style]="{ width: '100%' }"
                  appendTo="body"
                />
              </td>
              <td>
                <input pInputText formControlName="description" />
              </td>
              <td>
                <p-button
                  icon="pi pi-times"
                  [rounded]="true"
                  [text]="true"
                  severity="danger"
                  (onClick)="removeLine(i)"
                  [disabled]="lines.length <= 2"
                  size="small"
                />
              </td>
            </tr>
          }
        </tbody>
        <tfoot>
          <tr class="totals-row">
            <td><strong>{{ 'COMMON.TOTAL' | translate }}</strong></td>
            <td class="amount" [class.balanced]="isBalanced" [class.unbalanced]="!isBalanced">
              <strong>{{ totalDebit | number:'1.2-2' }}</strong>
            </td>
            <td class="amount" [class.balanced]="isBalanced" [class.unbalanced]="!isBalanced">
              <strong>{{ totalCredit | number:'1.2-2' }}</strong>
            </td>
            <td colspan="3">
              @if (!isBalanced) {
                <span class="balance-warning">
                  <i class="pi pi-exclamation-triangle"></i>
                  {{ 'JOURNAL_ENTRIES.NOT_BALANCED' | translate }}
                  ({{ 'JOURNAL_ENTRIES.DIFFERENCE' | translate }}: {{ totalDebit - totalCredit | number:'1.2-2' }})
                </span>
              } @else {
                <span class="balance-ok">
                  <i class="pi pi-check-circle"></i>
                  {{ 'JOURNAL_ENTRIES.BALANCED' | translate }}
                </span>
              }
            </td>
          </tr>
        </tfoot>
      </table>
    </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' | translate"
      icon="pi pi-check"
      (onClick)="onSave()"
      [loading]="!!(saving$ | async)"
      [disabled]="!isBalanced || lines.length < 2"
    />
  </div>
</app-form-dialog>

<!-- View Dialog -->
<p-dialog
  [header]="'JOURNAL_ENTRIES.VIEW_ENTRY' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '800px' }"
  [closable]="true"
>
  @if (viewingEntry(); as entry) {
    <div class="view-entry">
      <div class="view-header-info">
        <div class="info-item">
          <label>{{ 'JOURNAL_ENTRIES.NUMBER' | translate }}</label>
          <span class="mono">{{ entry.entry_number || ('JOURNAL_ENTRIES.DRAFT_NUMBER' | translate) }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'JOURNAL_ENTRIES.DATE' | translate }}</label>
          <span>{{ entry.date }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'COMMON.STATUS' | translate }}</label>
          <p-tag
            [value]="'JOURNAL_ENTRIES.STATUS_' + entry.status.toUpperCase() | translate"
            [severity]="getStatusSeverity(entry.status)"
          />
        </div>
        @if (entry.fiscal_year) {
          <div class="info-item">
            <label>{{ 'JOURNAL_ENTRIES.FISCAL_YEAR' | translate }}</label>
            <span>{{ entry.fiscal_year.name }}</span>
          </div>
        }
        @if (entry.reference) {
          <div class="info-item">
            <label>{{ 'JOURNAL_ENTRIES.REFERENCE' | translate }}</label>
            <span>{{ entry.reference }}</span>
          </div>
        }
        @if (entry.source_type) {
          <div class="info-item">
            <label>{{ 'JOURNAL_ENTRIES.SOURCE' | translate }}</label>
            @if (getSourceRoute(entry.source_type)) {
              <p-tag [value]="getSourceLabel(entry.source_type)" severity="info" [rounded]="true"
                class="source-link" (click)="navigateToSource(entry); viewDialogVisible.set(false)"
                [pTooltip]="'JOURNAL_ENTRIES.GO_TO_SOURCE' | translate" tooltipPosition="top" />
            } @else {
              <p-tag [value]="getSourceLabel(entry.source_type)" severity="secondary" [rounded]="true" />
            }
          </div>
        }
      </div>
      @if (entry.description) {
        <div class="view-description">
          <label>{{ 'JOURNAL_ENTRIES.DESCRIPTION' | translate }}</label>
          <p>{{ entry.description }}</p>
        </div>
      }
      <table class="view-lines-table">
        <thead>
          <tr>
            <th>{{ 'JOURNAL_ENTRIES.ACCOUNT' | translate }}</th>
            <th>{{ 'JOURNAL_ENTRIES.DEBIT' | translate }}</th>
            <th>{{ 'JOURNAL_ENTRIES.CREDIT' | translate }}</th>
            <th>{{ 'JOURNAL_ENTRIES.LINE_DESC' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (line of entry.lines; track $index) {
            <tr>
              <td>
                @if (line.account) {
                  <span class="mono">{{ line.account.code }}</span> - {{ line.account.name_ar || line.account.name }}
                } @else {
                  {{ getAccountName(line.account_id, (accounts$ | async) || []) }}
                }
              </td>
              <td class="amount">{{ line.debit | number:'1.2-2' }}</td>
              <td class="amount">{{ line.credit | number:'1.2-2' }}</td>
              <td>{{ line.description }}</td>
            </tr>
          }
        </tbody>
        <tfoot>
          <tr>
            <td><strong>{{ 'COMMON.TOTAL' | translate }}</strong></td>
            <td class="amount"><strong>{{ entry.total_debit | number:'1.2-2' }}</strong></td>
            <td class="amount"><strong>{{ entry.total_credit | number:'1.2-2' }}</strong></td>
            <td></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>
