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

<div class="page-container">
  <div class="page-header">
    <div class="header-text">
      <h1>{{ 'YEAR_END_CLOSING.TITLE' | translate }}</h1>
      <p>{{ 'YEAR_END_CLOSING.SUBTITLE' | translate }}</p>
    </div>
    <div class="header-actions">
      <p-button icon="pi pi-refresh" [rounded]="true" [text]="true" severity="secondary" (onClick)="retry()" pTooltip="Refresh" />
    </div>
  </div>

  <div class="info-banner">
    <i class="pi pi-info-circle"></i>
    <span>{{ 'YEAR_END_CLOSING.INFO_TEXT' | translate }}</span>
  </div>

  @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="table-card">
      <p-table [value]="(fiscalYears$ | async) || []" styleClass="p-datatable-sm">
        <ng-template #header>
          <tr>
            <th>{{ 'YEAR_END_CLOSING.FISCAL_YEAR' | translate }}</th>
            <th>{{ 'YEAR_END_CLOSING.START_DATE' | translate }}</th>
            <th>{{ 'YEAR_END_CLOSING.END_DATE' | translate }}</th>
            <th>{{ 'YEAR_END_CLOSING.CLOSING_STATUS' | translate }}</th>
            <th>{{ 'YEAR_END_CLOSING.FINANCIAL_SUMMARY' | translate }}</th>
            <th>{{ 'COMMON.ACTIONS' | translate }}</th>
          </tr>
        </ng-template>
        <ng-template #body let-fy>
          <tr>
            <td><strong>{{ fy.name }}</strong></td>
            <td>{{ fy.start_date }}</td>
            <td>{{ fy.end_date }}</td>
            <td>
              @if (getClosingForFY(fy.id); as closing) {
                <p-tag [value]="closing.status" [severity]="getStatusSeverity(closing.status)" />
                @if (closing.executed_at) {
                  <br><small class="text-text-secondary">{{ closing.executed_at | date:'short' }}</small>
                }
              } @else {
                <p-tag value="open" severity="info" />
              }
            </td>
            <td>
              @if (getClosingForFY(fy.id); as closing) {
                @if (closing.total_revenue !== null) {
                  <div class="text-sm">
                    <div>{{ 'YEAR_END_CLOSING.REVENUE' | translate }}: <strong class="text-green-500">{{ closing.total_revenue | number:'1.2-3' }}</strong></div>
                    <div>{{ 'YEAR_END_CLOSING.EXPENSES' | translate }}: <strong class="text-red-500">{{ closing.total_expenses | number:'1.2-3' }}</strong></div>
                    <div>{{ 'YEAR_END_CLOSING.NET_INCOME' | translate }}: <strong>{{ closing.net_income | number:'1.2-3' }}</strong></div>
                  </div>
                }
              } @else {
                <span class="text-text-secondary">—</span>
              }
            </td>
            <td>
              <div class="flex gap-1 flex-wrap">
                <p-button
                  icon="pi pi-check-circle"
                  [label]="'YEAR_END_CLOSING.CHECK_READINESS' | translate"
                  severity="info"
                  [outlined]="true"
                  size="small"
                  (onClick)="checkReadiness(fy)"
                  [loading]="checkingReadiness() && selectedFY()?.id === fy.id"
                />
                @if (!getClosingForFY(fy.id) || getClosingForFY(fy.id)?.status === 'reopened') {
                  <p-button
                    icon="pi pi-lock"
                    [label]="'YEAR_END_CLOSING.EXECUTE' | translate"
                    severity="danger"
                    [outlined]="true"
                    size="small"
                    (onClick)="openExecuteDialog(fy)"
                  />
                }
                @if (getClosingForFY(fy.id)?.status === 'completed') {
                  <p-button
                    icon="pi pi-lock-open"
                    [label]="'YEAR_END_CLOSING.REOPEN' | translate"
                    severity="warn"
                    [outlined]="true"
                    size="small"
                    (onClick)="reopenYear(fy)"
                  />
                }
              </div>
            </td>
          </tr>
        </ng-template>
        <ng-template #emptymessage>
          <tr><td colspan="6" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td></tr>
        </ng-template>
      </p-table>
    </div>
  }
</div>

<!-- Readiness Check Dialog -->
<p-dialog
  [header]="'YEAR_END_CLOSING.READINESS_TITLE' | translate"
  [(visible)]="readinessDialogVisible"
  [modal]="true"
  [style]="{ width: '500px' }"
>
  @if (readiness(); as r) {
    <div class="readiness-checks">
      @if (r.ready) {
        <div class="check-item pass">
          <i class="pi pi-check-circle" style="color: var(--color-success);"></i>
          <span>{{ 'YEAR_END_CLOSING.ALL_READY' | translate }}</span>
        </div>
      } @else {
        @for (issue of r.issues; track issue) {
          <div class="check-item fail">
            <i class="pi pi-times-circle" style="color: var(--color-danger);"></i>
            <span>{{ issue }}</span>
          </div>
        }
      }
      @if (r.summary) {
        <div class="summary-section">
          <div class="summary-row">
            <span>{{ 'YEAR_END_CLOSING.REVENUE' | translate }}</span>
            <strong style="color: var(--color-success);">{{ r.summary.total_revenue | number:'1.2-3' }}</strong>
          </div>
          <div class="summary-row">
            <span>{{ 'YEAR_END_CLOSING.EXPENSES' | translate }}</span>
            <strong style="color: var(--color-danger);">{{ r.summary.total_expenses | number:'1.2-3' }}</strong>
          </div>
          <div class="summary-row">
            <span>{{ 'YEAR_END_CLOSING.NET_INCOME' | translate }}</span>
            <strong>{{ r.summary.net_income | number:'1.2-3' }}</strong>
          </div>
        </div>
      }
    </div>
    <div class="readiness-status">
      @if (isAllReady()) {
        <p-tag value="Ready" severity="success" icon="pi pi-check" />
      } @else {
        <p-tag value="Not Ready" severity="danger" icon="pi pi-times" />
      }
    </div>
  }
  <ng-template #footer>
    <p-button [label]="'COMMON.CLOSE' | translate" severity="secondary" (onClick)="readinessDialogVisible.set(false)" />
    @if (isAllReady() && selectedFY()) {
      <p-button [label]="'YEAR_END_CLOSING.PROCEED_EXECUTE' | translate" icon="pi pi-arrow-right" severity="danger" (onClick)="readinessDialogVisible.set(false); openExecuteDialog(selectedFY()!)" />
    }
  </ng-template>
</p-dialog>

<!-- Execute Closing Dialog -->
<p-dialog
  [header]="'YEAR_END_CLOSING.EXECUTE_TITLE' | translate"
  [(visible)]="dialogVisible"
  [modal]="true"
  [style]="{ width: '550px' }"
>
  <form [formGroup]="executeForm" class="dialog-form">
    <div class="form-field">
      <label>{{ 'YEAR_END_CLOSING.INCOME_SUMMARY_ACCOUNT' | translate }} *</label>
      <p-select formControlName="income_summary_account_id" [options]="accountOptions" optionLabel="label" optionValue="value" [filter]="true" [placeholder]="'COMMON.SELECT' | translate" [style]="{'width':'100%'}" />
    </div>
    <div class="form-field">
      <label>{{ 'YEAR_END_CLOSING.RETAINED_EARNINGS_ACCOUNT' | translate }} *</label>
      <p-select formControlName="retained_earnings_account_id" [options]="accountOptions" optionLabel="label" optionValue="value" [filter]="true" [placeholder]="'COMMON.SELECT' | translate" [style]="{'width':'100%'}" />
    </div>
    <div class="form-field">
      <label>{{ 'YEAR_END_CLOSING.NOTES' | translate }}</label>
      <textarea pTextarea formControlName="notes" [rows]="3" [style]="{'width':'100%'}"></textarea>
    </div>
    <div class="form-field">
      <label>{{ 'YEAR_END_CLOSING.NOTES_AR' | translate }}</label>
      <textarea pTextarea formControlName="notes_ar" [rows]="3" [style]="{'width':'100%'}" dir="rtl"></textarea>
    </div>
  </form>
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="dialogVisible.set(false)" />
    <p-button [label]="'YEAR_END_CLOSING.EXECUTE' | translate" icon="pi pi-lock" severity="danger" (onClick)="executeClosing()" [loading]="executing()" [disabled]="!executeForm.valid" />
  </ng-template>
</p-dialog>
