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

<div class="accounts-page">
  <app-page-header title="ACCOUNTS.TITLE" subtitle="ACCOUNTS.SUBTITLE" (refresh)="retry()">
    <p-button
      [label]="'ACCOUNTS.IMPORT_TEMPLATE' | translate"
      icon="pi pi-download"
      severity="warn"
      [outlined]="true"
      (onClick)="openImportDialog()"
    />
    <p-button
      [label]="'ACCOUNTS.EXPAND_ALL' | translate"
      icon="pi pi-angle-double-down"
      severity="secondary"
      [text]="true"
      (onClick)="expandAll()"
    />
    <p-button
      [label]="'ACCOUNTS.COLLAPSE_ALL' | translate"
      icon="pi pi-angle-double-up"
      severity="secondary"
      [text]="true"
      (onClick)="collapseAll()"
    />
    <p-button
      [label]="'ACCOUNTS.NEW_ACCOUNT' | translate"
      icon="pi pi-plus"
      (onClick)="openNew()"
    />
  </app-page-header>

  @if (loading$ | async) {
    <div class="loading-state">
      <p-progressSpinner strokeWidth="3" />
      <p>{{ 'COMMON.LOADING' | translate }}</p>
    </div>
  } @else if (error$ | async; as error) {
    <div class="error-state">
      <i class="pi pi-exclamation-triangle"></i>
      <p>{{ error }}</p>
      <p-button
        [label]="'COMMON.RETRY' | translate"
        icon="pi pi-refresh"
        (onClick)="retry()"
        severity="secondary"
      />
    </div>
  } @else {
    <div class="search-bar">
      <span class="p-input-icon-start" style="width: 100%; max-width: 400px;">
        <i class="pi pi-search"></i>
        <input
          pInputText
          [placeholder]="'ACCOUNTS.SEARCH' | translate"
          [ngModel]="searchQuery"
          (ngModelChange)="onSearch($event)"
          style="width: 100%;"
        />
      </span>
    </div>
    <div class="table-card">
      <p-table
        [value]="visibleRows"
        [paginator]="false"
        dataKey="id"
        [scrollable]="true"
        scrollHeight="calc(100vh - 220px)"
        styleClass="p-datatable-sm"
      >
        <ng-template #header>
          <tr>
            <th style="width: 120px;">{{ 'ACCOUNTS.CODE' | translate }}</th>
            <th>{{ 'ACCOUNTS.NAME_AR' | translate }}</th>
            <th style="width: 120px;">{{ 'ACCOUNTS.CLASSIFICATION' | translate }}</th>
            <th style="width: 80px;">{{ 'ACCOUNTS.NATURE' | translate }}</th>
            <th style="width: 90px;">{{ 'ACCOUNTS.ACCOUNT_TYPE' | translate }}</th>
            <th style="width: 120px;">{{ 'COMMON.ACTIONS' | translate }}</th>
          </tr>
        </ng-template>
        <ng-template #body let-account>
          <tr [class.row-header]="account.account_type === 'header'"
              [class.row-depth-0]="account.depth === 0"
              [class.row-depth-1]="account.depth === 1">
            <td class="mono">{{ account.code }}</td>
            <td class="name-cell" (click)="toggleExpand(account)">
              <span class="name-content" [style.padding-inline-start.rem]="account.depth * 1.5">
                @if (account.hasChildren) {
                  <i class="pi toggle-icon"
                     [class.pi-chevron-down]="account.expanded"
                     [class.pi-chevron-right]="!account.expanded"
                  ></i>
                } @else {
                  <span class="toggle-spacer"></span>
                }
                @if (account.account_type === 'header') {
                  <i class="pi pi-folder" [class.pi-folder-open]="account.expanded" style="color: var(--color-accent);"></i>
                } @else {
                  <i class="pi pi-file" style="color: #90a4ae;"></i>
                }
                <span class="account-name">{{ account.name_ar }}</span>
              </span>
            </td>
            <td>
              <p-tag
                [value]="account.classification"
                [severity]="getClassificationSeverity(account.classification)"
                [style]="{'font-size': '0.7rem'}"
              />
            </td>
            <td>
              <span class="nature-badge" [class.debit]="account.nature === 'debit'" [class.credit]="account.nature === 'credit'">
                {{ account.nature === 'debit' ? ('ACCOUNTS.NATURE_DEBIT' | translate) : ('ACCOUNTS.NATURE_CREDIT' | translate) }}
              </span>
            </td>
            <td>
              <span class="type-badge" [class.header-type]="account.account_type === 'header'">
                {{ account.account_type === 'header' ? ('ACCOUNTS.TYPE_HEADER' | translate) : ('ACCOUNTS.TYPE_DETAIL' | translate) }}
              </span>
            </td>
            <td>
              <div class="action-buttons">
                <p-button
                  icon="pi pi-plus"
                  [rounded]="true"
                  [text]="true"
                  severity="success"
                  size="small"
                  (onClick)="addChild(account)"
                />
                <p-button
                  icon="pi pi-pencil"
                  [rounded]="true"
                  [text]="true"
                  severity="info"
                  size="small"
                  (onClick)="editAccount(account)"
                  [disabled]="account.is_system"
                />
                <p-button
                  icon="pi pi-trash"
                  [rounded]="true"
                  [text]="true"
                  severity="danger"
                  size="small"
                  (onClick)="deleteAccount(account)"
                  [disabled]="account.is_system || account.hasChildren"
                />
              </div>
            </td>
          </tr>
        </ng-template>
        <ng-template #emptymessage>
          <tr>
            <td colspan="6" class="text-center">
              <div class="empty-state">
                <i class="pi pi-sitemap"></i>
                <p>{{ 'COMMON.NO_DATA' | translate }}</p>
                <p-button
                  [label]="'ACCOUNTS.IMPORT_TEMPLATE' | translate"
                  icon="pi pi-download"
                  severity="warn"
                  (onClick)="openImportDialog()"
                />
              </div>
            </td>
          </tr>
        </ng-template>
      </p-table>
    </div>
  }
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingAccount() ? ('ACCOUNTS.EDIT_ACCOUNT' | translate) : ('ACCOUNTS.NEW_ACCOUNT' | translate)"
  [saving]="!!(saving$ | async)"
  [width]="'650px'"
  (save)="onSave()"
>
  <form [formGroup]="accountForm" class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'ACCOUNTS.CODE' | translate }} *</label>
        <input pInputText formControlName="code" />
        @if (accountForm.get('code')?.touched && accountForm.get('code')?.hasError('required')) {
          <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
        }
      </div>
      <div class="form-field">
        <label>{{ 'ACCOUNTS.ACCOUNT_TYPE' | translate }} *</label>
        <p-select formControlName="account_type" [options]="accountTypeOptions" optionLabel="label" optionValue="value" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'ACCOUNTS.NAME_AR' | translate }} *</label>
        <input pInputText formControlName="name_ar" />
        @if (accountForm.get('name_ar')?.touched && accountForm.get('name_ar')?.hasError('required')) {
          <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
        }
      </div>
      <div class="form-field">
        <label>{{ 'ACCOUNTS.NAME_EN' | translate }}</label>
        <input pInputText formControlName="name_en" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'ACCOUNTS.CLASSIFICATION' | translate }} *</label>
        <p-select formControlName="classification" [options]="classificationOptions" optionLabel="label" optionValue="value" />
      </div>
      <div class="form-field">
        <label>{{ 'ACCOUNTS.NATURE' | translate }} *</label>
        <p-select formControlName="nature" [options]="natureOptions" optionLabel="label" optionValue="value" />
      </div>
    </div>
    <div class="form-field">
      <label>{{ 'ACCOUNTS.PARENT' | translate }}</label>
      <p-select
        formControlName="parent_id"
        [options]="parentAccounts"
        optionLabel="name_ar"
        optionValue="id"
        [filter]="true"
        filterBy="name_ar,name_en,code"
        [showClear]="true"
        [placeholder]="'ACCOUNTS.SELECT_PARENT' | translate"
        appendTo="body"
      />
    </div>
    <div class="form-field">
      <label>{{ 'ACCOUNTS.DESCRIPTION' | translate }}</label>
      <input pInputText formControlName="description" />
    </div>
  </form>
</app-form-dialog>

<!-- Import Template Dialog -->
<p-dialog
  [(visible)]="importDialogVisible"
  [header]="'ACCOUNTS.IMPORT_TEMPLATE_TITLE' | translate"
  [modal]="true"
  [style]="{ width: '700px' }"
  [closable]="!importingTemplate()"
  [draggable]="false"
>
  @if (importingTemplate()) {
    <div class="import-progress">
      <p-progressSpinner strokeWidth="3" [style]="{ width: '48px', height: '48px' }" />
      <p class="progress-text">{{ 'ACCOUNTS.IMPORTING' | translate }}</p>
      <p class="progress-detail">
        {{ 'ACCOUNTS.IMPORT_PROGRESS' | translate:{ current: importProgress(), total: importTotal() } }}
      </p>
      <p-progressBar [value]="importTotal() > 0 ? (importProgress() / importTotal()) * 100 : 0" [showValue]="false" />
    </div>
  } @else {
    <p class="import-desc">{{ 'ACCOUNTS.IMPORT_TEMPLATE_DESC' | translate }}</p>

    <div class="template-grid">
      @for (tpl of templates; track tpl.id) {
        <div
          class="template-card"
          [class.selected]="selectedTemplate()?.id === tpl.id"
          (click)="selectTemplate(tpl)"
        >
          <div class="tpl-icon">
            <i [class]="tpl.icon"></i>
          </div>
          <div class="tpl-info">
            <h4>{{ tpl.name_ar }}</h4>
            <p class="tpl-name-en">{{ tpl.name_en }}</p>
            <p class="tpl-desc">{{ tpl.description_ar }}</p>
            <span class="tpl-count">{{ countTemplateAccounts(tpl) }} {{ 'ACCOUNTS.ACCOUNTS_COUNT' | translate:{ count: '' } }}</span>
          </div>
          @if (selectedTemplate()?.id === tpl.id) {
            <i class="pi pi-check-circle selected-check"></i>
          }
        </div>
      }
    </div>

    @if (selectedTemplate()) {
      <div class="import-confirm-section">
        <div class="warn-box">
          <i class="pi pi-exclamation-triangle"></i>
          <span>{{ 'ACCOUNTS.IMPORT_TEMPLATE_WARN' | translate }}</span>
        </div>
        <div class="confirm-input">
          <label>{{ 'ACCOUNTS.IMPORT_CONFIRM' | translate }}</label>
          <input
            pInputText
            [(ngModel)]="importConfirmText"
            [placeholder]="'ACCOUNTS.IMPORT_CONFIRM_PLACEHOLDER' | translate"
          />
        </div>
      </div>
    }

    <div class="import-actions">
      <p-button
        [label]="'COMMON.CANCEL' | translate"
        severity="secondary"
        [text]="true"
        (onClick)="importDialogVisible.set(false)"
      />
      <p-button
        [label]="'ACCOUNTS.IMPORT_TEMPLATE' | translate"
        icon="pi pi-download"
        severity="warn"
        [disabled]="!canImport"
        (onClick)="executeImport()"
      />
    </div>
  }
</p-dialog>
