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

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

  <ng-template #bodyTpl let-item>
      <tr>
        <td>{{ item.fiscal_year?.name || item.fiscal_year?.name_en || '-' }}</td>
        <td class="amount">{{ item.total_debit | number:'1.2-2' }}</td>
        <td class="amount">{{ item.total_credit | number:'1.2-2' }}</td>
        <td>{{ item.lines?.length || 0 }}</td>
        <td>
          <p-tag [value]="'OPENING_BALANCES.STATUS_' + item.status.toUpperCase() | translate"
                 [severity]="getStatusSeverity(item.status)" />
        </td>
        <td>
          <div class="action-buttons">
            <p-button icon="pi pi-eye" [rounded]="true" [text]="true" severity="info" (onClick)="view(item)"
                      [pTooltip]="'OPENING_BALANCES.VIEW' | translate" tooltipPosition="top" />
            <p-button icon="pi pi-search" [rounded]="true" [text]="true" severity="info" (onClick)="openReview(item)"
                      [pTooltip]="'OPENING_BALANCES.REVIEW' | translate" tooltipPosition="top" />
            <p-button icon="pi pi-file" [rounded]="true" [text]="true" severity="info" (onClick)="openAddInvoice(item)"
                      [pTooltip]="'OPENING_BALANCES.ADD_INVOICE' | translate" tooltipPosition="top" />
            @if (item.status === 'draft') {
              <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" (onClick)="edit(item)" />
              <p-button icon="pi pi-check-circle" [rounded]="true" [text]="true" severity="success"
                        (onClick)="confirm(item)" [pTooltip]="'OPENING_BALANCES.CONFIRM_ACTION' | translate" tooltipPosition="top" />
              <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" (onClick)="delete(item)" />
            }
            @if (item.status === 'confirmed') {
              <p-button icon="pi pi-lock" [rounded]="true" [text]="true" severity="warn" (onClick)="lockBalance(item)"
                        [pTooltip]="'OPENING_BALANCES.LOCK' | translate" tooltipPosition="top" />
              <p-button icon="pi pi-lock-open" [rounded]="true" [text]="true" severity="info" (onClick)="unlockBalance(item)"
                        [pTooltip]="'OPENING_BALANCES.UNLOCK' | translate" tooltipPosition="top" />
            }
          </div>
        </td>
      </tr>
    </ng-template>
  <app-data-table
    [data]="tableData()"
    [loading]="tableLoading()"
    [lazy]="true"
    [totalRecords]="totalRecords()"
    [first]="first"
    (onLazyLoad)="onPageChange($event)"
    (retry)="retry()"
    [columns]="columns"
    [bodyTpl]="bodyTpl"
  >
  </app-data-table>
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editing() ? ('OPENING_BALANCES.EDIT' | translate) : ('OPENING_BALANCES.NEW' | translate)"
  [saving]="!!(saving$ | async)"
  (save)="onSave()"
  width="850px"
>
  <form [formGroup]="form" class="ob-form">
    <div class="form-header-row">
      <div class="form-field">
        <label>{{ 'OPENING_BALANCES.FISCAL_YEAR' | translate }} *</label>
        <p-select formControlName="fiscal_year_id" [options]="(fiscalYears$ | async) || []" optionLabel="name" optionValue="id"
                  [placeholder]="'COMMON.SELECT' | translate" [style]="{ width: '100%' }" appendTo="body" />
      </div>
      <div class="form-field grow">
        <label>{{ 'OPENING_BALANCES.NOTES' | translate }}</label>
        <input pInputText formControlName="notes" />
      </div>
    </div>

    <div class="lines-section">
      <div class="lines-header">
        <h3>{{ 'OPENING_BALANCES.LINES' | translate }}</h3>
        <p-button icon="pi pi-plus" [label]="'OPENING_BALANCES.ADD_LINE' | translate" severity="secondary" [outlined]="true" size="small" (onClick)="addLine()" />
      </div>
      <table class="lines-table" formArrayName="lines">
        <thead>
          <tr>
            <th class="col-account">{{ 'OPENING_BALANCES.ACCOUNT' | translate }}</th>
            <th class="col-amount">{{ 'OPENING_BALANCES.DEBIT' | translate }}</th>
            <th class="col-amount">{{ 'OPENING_BALANCES.CREDIT' | translate }}</th>
            <th class="col-desc">{{ 'OPENING_BALANCES.DESCRIPTION' | translate }}</th>
            <th class="col-action"></th>
          </tr>
        </thead>
        <tbody>
          @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]="'COMMON.SELECT' | translate"
                          [style]="{ width: '100%' }" appendTo="body">
                  <ng-template #item let-a><span>{{ a.code }} - {{ a.name_ar }}</span></ng-template>
                  <ng-template #selectedItem let-a><span>{{ a.code }} - {{ a.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><input pInputText formControlName="description" /></td>
              <td><p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="danger" (onClick)="removeLine(i)" size="small" [disabled]="lines.length <= 1" /></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="2">
              @if (!isBalanced) {
                <span class="balance-warning"><i class="pi pi-exclamation-triangle"></i> {{ 'OPENING_BALANCES.NOT_BALANCED' | translate }}</span>
              } @else {
                <span class="balance-ok"><i class="pi pi-check-circle"></i> {{ 'OPENING_BALANCES.BALANCED' | translate }}</span>
              }
            </td>
          </tr>
        </tfoot>
      </table>
    </div>
  </form>
</app-form-dialog>

<!-- View Dialog -->
<p-dialog [header]="'OPENING_BALANCES.VIEW' | translate" [(visible)]="viewDialogVisible" [modal]="true" [style]="{ width: '750px' }" [closable]="true">
  @if (viewing(); as ob) {
    <div class="view-info">
      <div class="info-row">
        <div class="info-item"><label>{{ 'OPENING_BALANCES.FISCAL_YEAR' | translate }}</label><span>{{ ob.fiscal_year?.name || '-' }}</span></div>
        <div class="info-item"><label>{{ 'COMMON.STATUS' | translate }}</label>
          <p-tag [value]="'OPENING_BALANCES.STATUS_' + ob.status.toUpperCase() | translate" [severity]="getStatusSeverity(ob.status)" />
        </div>
        <div class="info-item"><label>{{ 'OPENING_BALANCES.TOTAL_DEBIT' | translate }}</label><span class="mono">{{ ob.total_debit | number:'1.2-2' }}</span></div>
        <div class="info-item"><label>{{ 'OPENING_BALANCES.TOTAL_CREDIT' | translate }}</label><span class="mono">{{ ob.total_credit | number:'1.2-2' }}</span></div>
      </div>
    </div>
    <p-table [value]="ob.lines" styleClass="p-datatable-sm">
      <ng-template #header>
        <tr>
          <th>{{ 'OPENING_BALANCES.ACCOUNT' | translate }}</th>
          <th>{{ 'OPENING_BALANCES.DEBIT' | translate }}</th>
          <th>{{ 'OPENING_BALANCES.CREDIT' | translate }}</th>
          <th>{{ 'OPENING_BALANCES.DESCRIPTION' | translate }}</th>
        </tr>
      </ng-template>
      <ng-template #body let-line>
        <tr>
          <td>
            @if (line.account) { <span class="mono">{{ line.account.code }}</span> - {{ line.account.name_ar || line.account.name }} }
            @else { {{ line.account_id }} }
          </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>
      </ng-template>
    </p-table>
  }
  <ng-template #footer>
    <p-button [label]="'COMMON.CLOSE' | translate" icon="pi pi-times" severity="secondary" (onClick)="viewDialogVisible.set(false)" />
  </ng-template>
</p-dialog>

<!-- Review Dialog -->
<p-dialog [header]="'OPENING_BALANCES.REVIEW' | translate" [(visible)]="reviewVisible" [modal]="true" [style]="{ width: '750px' }" [closable]="true">
  @if (reviewData(); as data) {
    <div class="review-content">
      @if (data.summary) {
        <div class="view-info">
          <div class="info-row">
            <div class="info-item"><label>{{ 'OPENING_BALANCES.TOTAL_DEBIT' | translate }}</label><span class="mono">{{ data.summary.total_debit | number:'1.2-2' }}</span></div>
            <div class="info-item"><label>{{ 'OPENING_BALANCES.TOTAL_CREDIT' | translate }}</label><span class="mono">{{ data.summary.total_credit | number:'1.2-2' }}</span></div>
          </div>
        </div>
      }
      @if (data.lines?.length) {
        <p-table [value]="data.lines" styleClass="p-datatable-sm">
          <ng-template #header>
            <tr>
              <th>{{ 'OPENING_BALANCES.ACCOUNT' | translate }}</th>
              <th>{{ 'OPENING_BALANCES.DEBIT' | translate }}</th>
              <th>{{ 'OPENING_BALANCES.CREDIT' | translate }}</th>
              <th>{{ 'OPENING_BALANCES.DESCRIPTION' | translate }}</th>
            </tr>
          </ng-template>
          <ng-template #body let-line>
            <tr>
              <td>
                @if (line.account) { <span class="mono">{{ line.account.code }}</span> - {{ line.account.name_ar || line.account.name }} }
                @else { {{ line.account_id }} }
              </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>
          </ng-template>
        </p-table>
      }
      @if (!data.lines?.length && !data.summary) {
        <pre style="white-space: pre-wrap; direction: ltr;">{{ data | json }}</pre>
      }
    </div>
  }
  <ng-template #footer>
    <p-button [label]="'COMMON.CLOSE' | translate" icon="pi pi-times" severity="secondary" (onClick)="reviewVisible.set(false)" />
  </ng-template>
</p-dialog>

<!-- Add Invoice Dialog -->
<p-dialog [header]="'OPENING_BALANCES.ADD_INVOICE' | translate" [(visible)]="invoiceDialogVisible" [modal]="true" [style]="{ width: '550px' }" [closable]="true">
  @if (invoiceForm) {
    <form [formGroup]="invoiceForm" class="dialog-form ob-form">
      <div class="form-field">
        <label>{{ 'OPENING_BALANCES.INVOICE_NUMBER' | translate }} *</label>
        <input pInputText formControlName="invoice_number" />
        @if (invoiceForm.get('invoice_number')?.touched && invoiceForm.get('invoice_number')?.hasError('required')) {
          <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
        }
      </div>
      <div class="form-field">
        <label>{{ 'OPENING_BALANCES.INVOICE_PARTNER' | translate }} *</label>
        <p-select formControlName="partner_id" [options]="(partners$ | async) || []" optionLabel="name_ar" optionValue="id"
                  [filter]="true" filterBy="name_ar,name_en,code" [placeholder]="'COMMON.SELECT' | translate"
                  [style]="{ width: '100%' }" appendTo="body" />
        @if (invoiceForm.get('partner_id')?.touched && invoiceForm.get('partner_id')?.hasError('required')) {
          <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
        }
      </div>
      <div class="form-header-row">
        <div class="form-field">
          <label>{{ 'OPENING_BALANCES.INVOICE_AMOUNT' | translate }} *</label>
          <p-inputNumber formControlName="amount" [min]="0.01" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="2" [style]="{ width: '100%' }" />
          @if (invoiceForm.get('amount')?.touched && invoiceForm.get('amount')?.hasError('required')) {
            <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
          }
        </div>
        <div class="form-field">
          <label>{{ 'OPENING_BALANCES.INVOICE_TYPE' | translate }} *</label>
          <p-select formControlName="type" [options]="invoiceTypeOptions" optionLabel="label" optionValue="value"
                    [style]="{ width: '100%' }" />
        </div>
      </div>
      <div class="form-field">
        <label>{{ 'OPENING_BALANCES.INVOICE_DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [style]="{ width: '100%' }" appendTo="body" />
        @if (invoiceForm.get('date')?.touched && invoiceForm.get('date')?.hasError('required')) {
          <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
        }
      </div>
    </form>
  }
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="invoiceDialogVisible.set(false)" />
    <p-button [label]="'COMMON.SAVE' | translate" icon="pi pi-check" (onClick)="onAddInvoice()" />
  </ng-template>
</p-dialog>
